multiple condition in r

Viewed 40

is there a better way to have multiple condition in order to simplify my code. here is an example of what I'm talking about.

library(data.table)
test <- data.table(dx1 <- c("a", "b", "c"),
                   dx2 <- c("b", "c", "d"),
                   dx3 <- c("a", "f", "g"))

condition <- c("a", "b")

# This is what I want to simplify
test[,dx4 := ifelse(dx1 %in% condition|
                    dx2 %in% condition |
                    dx3 %in% condition, 1, 0)]

Thank you

1 Answers

We can use Reduce with |. Specify the columns of interest in .SDcols (not needed if all the columns are used), loop over the Subset of Data.table (.SD), check whether the the 'condition' elements are %in% the column, Reduce it to a logical vector with | and convert to binary with as.integer or +

test[, dx4 := +(Reduce(`|`, lapply(.SD, `%in%`, condition))), .SDcols = dx1:dx3]
test
#   dx1 dx2 dx3 dx4
#1:   a   b   a   1
#2:   b   c   f   1
#3:   c   d   g   0

data

test <- data.table(dx1 = c("a", "b", "c"),
               dx2 = c("b", "c", "d"),
               dx3 = c("a", "f", "g"))
Related