【问题标题】:Subset all rows by group by type按类型对所有行进行分组
【发布时间】:2017-06-27 16:50:12
【问题描述】:

我有一个数据框:

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")) 我基本上想保留包含项目类型“a”的事务的所有行

所以我的输出看起来像:

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

我将如何编写代码以仅处理包含 a&b 的事务?

【问题讨论】:

  • df[df$transaction %in% unique(df$transaction[df$itemType == 'a']),]

标签: r subset


【解决方案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 ) ,   ]

【讨论】:

  • 感谢您的回答。我知道这种可能性,但我需要所有包含 a 的交易行。
  • 感谢您的回答。你能解释一下这两行吗?
  • @daveDo - 添加注释
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-19
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多