Q:

Find the index of the row in data frame that contain one element in a string vector

If I have a data.frame like this
df <- data.frame(col1 = c(letters[1:4],"a"),col2 = 1:5,col3 = letters[10:14])
 df
   col1 col2 col3
1    a    1    j
2    b    2    k
3    c    3    l
4    d    4    m
5    a    5    n

I want to get the row indices that contains one of the element in c("a", "k", "n"); in this example, the result should be 1, 2, 5.

A:

If you have a large data frame and you wish to check all columns, try this
x <- c("a", "k", "n")

Reduce(union, lapply(x, function(a) which(rowSums(df == a) > 0)))
# [1] 1 5 2

and of course you can sort the end result.

