0

可能重复:
在矩阵 R 子集中选择行的一些值
具有多个键的数据帧

说我有一个清单

> 测试

  V1    V2   V3
1  1   one  uno
2  2   two duos
3  3 three tres
4  4 four cuatro

和一个向量a<-c("one","three")

我想获取列表的子集,test其中第二列的元素来自 vector a

所以在这种情况下,答案应该是这样的,

  V1    V2   V3
1  1   one  uno
2  3 three tres

我想要一些 test[test[,2]=="one",]符合多个值的东西。怎么做?

4

1 回答 1

4

您正在寻找的是%in%(尽管您也可以使用matchand subset)。见下文。

df <- data.frame(V1=1:4, V2=c("one", "two", "three", "four"), stringsAsFactors = FALSE)
fil <- c("one", "three")

> df
#   V1    V2
# 1  1   one
# 2  2   two
# 3  3 three
# 4  4  four

> fil
# [1] "one"   "three"

# subset df by column V2 using fil

# using %in%
df[df$V2 %in% fil, ]

# using subset
subset(df, V2 %in% fil)

# using match
df[!is.na(match(df$V2, fil)), ] # (or) 
df[which(!is.na(match(df$V2, fil))), ]

# all gives
#   V1    V2
# 1  1   one
# 3  3 three
于 2013-01-26T10:23:51.927 回答