3

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)]
1
  • Have a look at ?%in%. Commented Apr 3, 2014 at 13:46

1 Answer 1

4

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"), ]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.