Add a column that shows whether the two previous columns include 0 or not

Viewed 44

I have a data.frame called dat. I want to add a new column to it called dif. Then, in each row if lower and upper range included 0 (e.g., -0.41 to 0.1 in 1st row) I want the dif value to show FALSE else (e.g., 0.10 to 0.2 2nd row) TRUE.

Is this possible to do in R for any similar data.frame (the following is a toy example a functional answer is appreciated)?

dat <- data.frame(lower = c(-0.41, .1, -.2), upper = 1:3*.1, row.names = paste("a", 1:3)) # add a column called `dif`


desired_output <- data.frame(lower = c(-0.41, .1, -.2), upper = 1:3*.1, dif = c(F,T,F), row.names = paste("a", 1:3))

4 Answers

You can use dplyr::between:

library(dplyr)

dat %>% 
  rowwise() %>% 
  mutate(dif = !between(0, lower, upper))

Output

# A tibble: 3 x 3
# Rowwise: 
  lower upper dif  
  <dbl> <dbl> <lgl>
1 -0.41   0.1 FALSE
2  0.1    0.2 TRUE 
3 -0.2    0.3 FALSE

You can use :

transform(dat, dif = lower > 0 | upper < 0)

#  lower upper   dif
#1 -0.41   0.1 FALSE
#2  0.10   0.2  TRUE
#3 -0.20   0.3 FALSE

We can use mutate from dplyr

library(dplyr)
mutate(dat, dif = lower > 0 | upper < 0)

Or an option in base R

Reduce(`|`, Map(function(x, y)  match.fun(y)(x, 0), dat, c(">", "<")))
#[1] FALSE  TRUE FALSE

Here is another base R option using do.call with *

dat$dif <- do.call("*", dat) > 0

such that

> dat
    lower upper   dif
a 1 -0.41   0.1 FALSE
a 2  0.10   0.2  TRUE
a 3 -0.20   0.3 FALSE
Related