Question

I have the following data frame

df <- data.frame(A1 = c("A","A","A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B"), 
             B2 = c("C","D","C","D","C","D","C","D","C","D","C","D","C","D","C","D","C","D","C","D"), 
             C3 = c("E","F","E","F","E","F","E","F","E","F","E","F","E","F","E","F","E","F","E","F"),
             D4=c(1,12,5,41,45,4,5,6,12,7,3,4,6,8,12,4,12,1,6,7))

and I would like to subset all the rows for which the first 3 column match the vector c("A","C","E")

I have tried to use which but it does not work

vct <- c("A","C","E")
df[which(df[1:3] == vct)]
Was it helpful?

Solution

You can probably use paste (or interaction):

vct <- c("A","C","E")
do.call(paste, df[1:3]) %in% paste(vct, collapse = " ")
#  [1]  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE FALSE
# [12] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
df[do.call(paste, df[1:3]) %in% paste(c("A", "C", "E"), collapse = " "), ]
#   A1 B2 C3 D4
# 1  A  C  E  1
# 3  A  C  E  5
# 5  A  C  E 45
# 7  A  C  E  5
# 9  A  C  E 12

## with "interaction"
df[interaction(df[1:3], drop=TRUE) %in% paste(vct, collapse = "."), ]

You can also do something like this:

df[with(df, A1 == "A" & B2 == "C" & C3 == "E"), ]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top