我有以下数据框
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))
我希望将前3列与向量c匹配的所有行(“A”,“C”,“E”)
我曾尝试使用哪种但不起作用
vct <- c("A","C","E")
df[which(df[1:3] == vct)]
答案 0 :(得分:4)
您可以使用paste
(或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 = "."), ]
您也可以这样做:
df[with(df, A1 == "A" & B2 == "C" & C3 == "E"), ]