Reputation: 296
I have a DF and would like to query multiple columns at the same time in an Auxiliary Table. DF Example
KEY <- c(123,456,789,111,222,333)
DAY_1 <- c('RICE','','RICE','','RICE','')
DAY_2 <- c('BEAN','','BEAN','','','BEAN')
DAY_3 <- c('POTATO','','POTATO','','POTATO','POTATO')
DAY_4 <- c('LETTUCE','LETTUCE','','LETTUCE','','LETTUCE')
DAY_5 <- c('STEAK','','STEAK','','STEAK','STEAK')
DF <- data.frame(KEY,DAY_1,DAY_2,DAY_3,DAY_4,DAY_5)
My Auxiliary Table
AUX <- c('RICE','BEAN')
TABLE_AUX <- data.frame(AUX)
Therefore, I would like to consult the 5 columns at the same time (DAY_1 to DAY_5) to check if the key consumed any food from the Auxiliary Table (rice OR beans).
As a result, I would like to see the following output:
KEY <- c(123,456,789,111,222,333)
DAY_1 <- c('RICE','','RICE','','RICE','')
DAY_2 <- c('BEAN','','BEAN','','','BEAN')
DAY_3 <- c('POTATO','','POTATO','','POTATO','POTATO')
DAY_4 <- c('LETTUCE','LETTUCE','','LETTUCE','','LETTUCE')
DAY_5 <- c('STEAK','','STEAK','','STEAK','STEAK')
TEST <- c('YES','NO','YES','NO','YES','YES')
DF <- data.frame(KEY,DAY_1,DAY_2,DAY_3,DAY_4,DAY_5,TEST)
Thanks!
Upvotes: 1
Views: 66
Reputation: 886948
There are multiple options to get the output. Either we loop over the rows, with apply
and MARGIN = 1
, check whether there are any
elements of 'AUX' %in%
the row, change the logical vector to "YES/NO" by changing to numeric index
nm1 <- grep("^DAY_\\d+$", names(DF), value = TRUE)
DF$TEST <- apply(DF[nm1], 1, function(x) c("NO", "YES")[any(x %in% AUX) + 1])
DF$TEST
#[1] "YES" "NO" "YES" "NO" "YES" "YES"
Or with lapply
and Reduce
c("NO", "YES")[Reduce(`|`, lapply(DF[nm1], `%in%`, AUX)) + 1]
Upvotes: 1