judge the values crossing zero

Viewed 79

I would like to determine whether or not the ranges of min and max values cross zero (0 = crossing zero, 1 = not crossing zero).

min <- c(0, -1, -1, 1, 1)
max <- c(1, 1, -0.1, 3, 1.5)
answer <- c(0, 0, 1, 1, 1)
data <- cbind(min,max, answer)
3 Answers

You can use the between function from dplyr:

library(dplyr)
min <- c(0, -1, -1, 1, 1)
max <- c(1, 1, -0.1, 3, 1.5)
df1 = data.frame(min,max) %>% 
  rowwise() %>% 
  mutate(answer = as.numeric(!between(0,min,max))) 

Or using base R:

df1 = data.frame(min,max)
df1$answer = apply(df1, 1, function(x) as.numeric(!(x[1]<= 0 & x[2] >=0)))

Base R vectorised answer -

transform(data, answer = as.integer(!(min <= 0 & max > 0)))

#  min  max answer
#1   0  1.0      0
#2  -1  1.0      0
#3  -1 -0.1      1
#4   1  3.0      1
#5   1  1.5      1

If you prefer dplyr the same can be written as -

library(dplyr)
data %>% mutate(answer = as.integer(!(min <= 0 & max > 0)))

data

min <- c(0, -1, -1, 1, 1)
max <- c(1, 1, -0.1, 3, 1.5)
data <- data.frame(min,max)

You can simply multiply them, as to cross you either need a negative product or one being zero.

answer <- ifelse(min * max <= 0, 0, 1)

or

answer <- as.integer(min * max > 0)

# [1] 0 0 1 1 1

If your 0 and 1 are not a requirement, even shorter to get a TRUE or FALSE

answer <- min * max <= 0
# [1]  TRUE  TRUE FALSE FALSE FALSE
Related