【问题标题】:R Data.Table Cut Data Into Groups And LabelR Data.Table 将数据分成组和标签
【发布时间】:2020-03-20 19:05:52
【问题描述】:
data1=data.frame("Score"=c(1,3,4,4,4,5,6,6,6,6,6),
"Group"=c(1,1,2,2,2,2,3,3,3,3,3),
"Group1"=c('Cat','Cat','Fox','Fox','Fox','Fox','Dog','Dog','Dog','Dog','Dog'))

我只有分数的“data1”。我希望添加组和组 1。规则是:

如果 0

如果 2

如果 5

【问题讨论】:

  • 'Score'的第二个值是3,所以应该属于'Fox'

标签: r data.table cut


【解决方案1】:

我们可以使用cut创建'Group',然后根据'Group'的数字索引,将'Group1'中的值替换为'Cat', 'Fox', 'Dog'

library(data.table)
setDT(data1)[, Group := as.integer(cut(Score, breaks = c(-Inf, 1, 4, 10)))][,
         Group1 := c('Cat', 'Fox', 'Dog')[Group]][]

【讨论】:

  • !完美的!我注意到当我这样做时它会更新“data1”但也会打印出数据。
  • @bvowe 打印出来是因为我最后使用了[]
猜你喜欢
  • 1970-01-01
  • 2015-05-12
  • 2015-08-04
  • 1970-01-01
  • 2019-02-16
  • 1970-01-01
  • 2014-09-14
  • 2015-08-02
  • 1970-01-01
相关资源
最近更新 更多