按多列聚合并从长到宽重塑

Aggregate by multiple columns and reshape from long to wide

SO 上有一些与此主题类似的问题,但与我的用例不完全相同。我有一个数据集,其中列的布局如下所示

     Id        Description          Value
     10        Cat                  19
     10        Cat                  20
     10        Cat                  5
     10        Cat                  13
     11        Cat                  17
     11        Cat                  23
     11        Cat                  7
     11        Cat                  14  
     10        Dog                  19
     10        Dog                  20
     10        Dog                  5
     10        Dog                  13
     11        Dog                  17
     11        Dog                  23
     11        Dog                  7
     11        Dog                  14    

我想做的是通过 ID、描述捕获值列的平均值。最终数据集如下所示。

     Id       Cat         Dog 
     10       14.25       28.5
     11       15.25       15.25

我可以用一种非常粗略的方式来做这件事,但效率不高

tempdf1 <- df %>%
  filter(str_detect(Description, "Cat")) %>%
   group_by(Id, Description) %>%
  summarize(Mean_Value = mean(Value) , na.rm = TRUE))

这不是很方便。非常感谢任何有关如何更有效地完成预期结果的建议。

您可以使用 data.table 聚合(计算平均值)每个组并使用 dcast():

获得想要的 table 格式
library(data.table)
foo <- setDT(d)[, mean(Value), .(Id, Description)]
#    Id Description    V1
# 1: 10         Cat 14.25
# 2: 11         Cat 15.25
# 3: 10         Dog 14.25
# 4: 11         Dog 15.25
dcast(foo, Id ~ Description, value.var = "V1")
#    Id   Cat   Dog
# 1: 10 14.25 14.25
# 2: 11 15.25 15.25

使用 dcast 甚至 acast 来自 reshape2()

dcast(dat,Id~Description,mean)
   Id   Cat   Dog
 1 10 14.25 14.25
 2 11 15.25 15.25

Base R 可能会更长一些:

 reshape(aggregate(.~Id+Description,dat,mean),direction = "wide",v.names  = "Value",idvar = "Id",timevar = "Description")
  Id Value.Cat Value.Dog
1 10     14.25     14.25
2 11     15.25     15.25

您可以使用 dplyr 执行 summarise 并使用 tidyr::spread 从长到宽的转换:

library(dplyr)
library(tidyr)

df %>%
    group_by(Id, Description) %>%
    summarise(Mean = mean(Value)) %>% 
    spread(Description, Mean)

     Id   Cat   Dog
* <int> <dbl> <dbl>
1    10 14.25 14.25
2    11 15.25 15.25

我会用 tapply:

with( dat, tapply(Value, list(Id,Description), mean))
     Cat   Dog
10 14.25 14.25
11 15.25 15.25

return 是矩阵对象所以不要尝试使用“$”访问。