Home > database >  judge the values crossing zero
judge the values crossing zero

Time:12-06

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)

CodePudding user response:

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)))

CodePudding user response:

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)
  • Related