按类型按组子集所有行

时间:2017-02-09 15:33:15

标签: r subset

我有一个数据框:

df <- data.frame(transaction= c(1,1,1,2,2,3,3,3,3,4,4,4), itemType = c("a","b","a","l","l","a","b","l","l","d","d","d")) 我基本上想要保留包含项类型&#34; a&#34;

的事务的所有行

所以我的输出看起来像:

  transaction itemType
1           1        a
2           1        b
3           1        a
4           3        a
5           3        b
6           3        l
7           3        l

我如何编写代码以仅采用包含&amp; b?

的交易

1 个答案:

答案 0 :(得分:-1)

我会使用索引

# save all the "transactions" where iteamtype equals "a" to an object called F  
f <-  df[ df$itemType %in% "a" , "transaction"  ]

#optional (look as f)
print(f)
print( unique(f))

# Subset to all the rows which equals one of the "transactions" stored in the object f
df[ df$transaction %in% unique( f ) ,   ]