【问题标题】:Aggregating over 2 columns of a dataframe R聚合数据框 R 的 2 列
【发布时间】:2016-05-18 20:51:54
【问题描述】:

我的数据框如下

TreeID    Species    PlotNo    Basalarea
12345       A          1         120
13242       B          7         310
14567       D          8         250
13245       B          1         305
13426       B          1         307
13289       A          3         118

我用过

newdata<- aggregate(Basalarea~PlotNo+Species, data, sum, na.rm=TRUE)

聚合所有的值使得

 newdata
     Species    PlotNo    Basalarea
       A          1         120
       A          3         118
       B          1         some value
       B          7         310
       D          8         250

这很好,但我想要一个这样的数据框

PlotNo    A       B            D
 1        120    some value    0
 3        118    0             0
 7        0      310           0
 8        0      0            250

如何获取上述dataframe?

【问题讨论】:

  • 请显示reproducible example 的数据以及您对解决方案的尝试。 SO 成员是帮助解决编程问题的志愿者。
  • 感谢您的建议。我提供了一个我想要获得的例子。希望有人帮助我!

标签: r aggregate-functions


【解决方案1】:

我们可以使用dcast 将长格式转换为宽格式。将fun.aggregate 指定为sum

library(reshape2)
dcast(df1, PlotNo~Species, value.var='Basalarea', sum)
#  PlotNo   A   B   D
#1      1 120 612   0
#2      3 118   0   0
#3      7   0 310   0
#4      8   0   0 250

或者base R 选项将使用xtabs。默认情况下,它会为 'PlotNo' 和 'Species' 的组合获取 'Basalarea' 的 sum

xtabs(Basalarea~PlotNo+Species, df1)
#     Species
#PlotNo   A   B   D
#     1 120 612   0
#     3 118   0   0
#     7   0 310   0
#     8   0   0 250

或者另一个base R选项是tapply

with(df1, tapply(Basalarea, list(PlotNo, Species), FUN=sum))

【讨论】:

  • 优秀的替代品,但 xtabs 不返回非数据框对象吗?而 tapply 不显示 PlotNo。
  • @Parfait 如果需要,可以使用as.data.frame.matrix(xtabs(.. 转换为data.frame。关于“PlotNo”,它只是输出的 row.names。因此,如果 OP 需要它,可以将其添加到新列中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-08
  • 1970-01-01
  • 2016-01-13
  • 2016-03-02
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
相关资源
最近更新 更多