check rowwise if value in one column is present in multiple other columns R

Viewed 17

brain stuck. i need to find a way to look for one column's rowwise value across multiple other columns, within the same row. like... 50 or 60. In the example below, "is rowwise value from A in B or C?" but using column positions within the actual data, not names of columns, as there are too many. i understand case_when would do the trick, but again too many columns to test.

example:

df1 <- data.frame(A = c(4, 6,3), 
                  B = c(4, 1, 1), 
                  C = c(1, 1, 3))

i tried this with map() but it seems to be looking in column 3 for any instance of number 4:59, not across columns 4 through 59.

nums <- c(4:59)
cols <- c(3)

wL$Check_Median <-
  wL[, cols] %>%
  map(~.x %in% nums) %>%
  reduce(`|`)

I imagined it would work, using 4:59 instead of named columns, something like this:

nums <- c(B:C)
cols <- c(A)

wL$D <-
  wL[, cols] %>%
  map(~.x %in% nums) %>%
  reduce(`|`)

and the result would be:

df2 <- data.frame(A = c(4, 6,3), 
                  B = c(4, 1, 1), 
                  C = c(1, 1, 3),
                  D = c(TRUE, FALSE, TRUE))
1 Answers

guess this one wasn't interesting enough for anyone..

here's a solution: wL$D <- Reduce(|, lapply(wL[28:52], ==, wL[,13]))

Related