表示基于 r 中单个列的所有其他列

Mean all other other columns based on a single column in r

我有一个包含 40,000 多列的大型数据框,我 运行 遇到了与此类似的问题 Sum by distinct column value in R

shop <- data.frame( 
  'shop_id' = c('Shop A', 'Shop A', 'Shop A', 'Shop B', 'Shop C', 'Shop C'), 
  'Assets' = c(2, 15, 7, 5, 8, 3),
  'Liabilities' = c(5, 3, 8, 9, 12, 8),
  'sale' = c(12, 5, 9, 15, 10, 18), 
  'profit' = c(3, 1, 3, 6, 5, 9))

我有一个列 shop_id 重复了很多次。我还有其他与 shop_id 相关的值,例如资产、负债、利润、损失等。我现在想对具有相同 shop_id 的所有变量求平均值,即我想要唯一的 shop_ids 并希望对具有相同 shop_id 的所有列进行平均。因为,有成千上万的变量(列)分别与每一列(变量)一起工作是非常乏味的。

我的回答应该是

 shop_id  Assets  Liabilities     sale    profit    
 Shop A   8.0     5.333333    8.666667  2.333333
 Shop B   5.0     9.000000   15.000000  6.000000
 Shop C   5.5    10.000000   14.000000  7.000000

我目前正在使用嵌套的 for 循环,如下所示: 与 R 一样多才多艺,我相信应该有更快的方法来做到这一点

idx <- split(1:nrow(shop), shop$shop_id)

newdata <- data.frame()

for( i in 1:length(idx)){
    newdata[i,1]<-c(names(idx)[i] )
    for (j in 2:ncol(shop)){
        newdata[i,j]<-mean(shop[unlist(idx[i]),j])
    }
}

使用 plyr 包中的 ddply 函数:

> require("plyr")
> ddply(shop, ~shop_id, summarise, Assets=mean(Assets),
        Liabilities=mean(Liabilities), sale=mean(sale), profit=mean(profit))

  shop_id Assets Liabilities      sale   profit
1  Shop A    8.0    5.333333  8.666667 2.333333
2  Shop B    5.0    9.000000 15.000000 6.000000
3  Shop C    5.5   10.000000 14.000000 7.000000

尝试data.table

library(data.table)
setDT(shop)[, lapply(.SD, mean), shop_id]
#  shop_id Assets Liabilities      sale   profit
#1:  Shop A    8.0    5.333333  8.666667 2.333333
#2:  Shop B    5.0    9.000000 15.000000 6.000000
#3:  Shop C    5.5   10.000000 14.000000 7.000000

library(dplyr)
shop %>% 
    group_by(shop_id)%>%
    summarise_each(funs(mean))
# shop_id Assets Liabilities      sale   profit
#1  Shop A    8.0    5.333333  8.666667 2.333333
#2  Shop B    5.0    9.000000 15.000000 6.000000
#3  Shop C    5.5   10.000000 14.000000 7.000000

aggregate(.~shop_id, shop, FUN=mean)
#   shop_id Assets Liabilities      sale   profit
#1  Shop A    8.0    5.333333  8.666667 2.333333
#2  Shop B    5.0    9.000000 15.000000 6.000000
#3  Shop C    5.5   10.000000 14.000000 7.000000

对于 40,000 列,我会使用 data.table 或者可能是 dplyr.

试试 dplyr :

library("dplyr")
shop %>% group_by(shop_id) %>% summarise_each(funs(mean))

#   shop_id Assets Liabilities      sale   profit
# 1  Shop A    8.0    5.333333  8.666667 2.333333
# 2  Shop B    5.0    9.000000 15.000000 6.000000
# 3  Shop C    5.5   10.000000 14.000000 7.000000

rowsum 可能会有所帮助,此处:

rowsum(shop[-1], shop[[1]]) / table(shop[[1]])
#       Assets Liabilities      sale   profit
#Shop A    8.0    5.333333  8.666667 2.333333
#Shop B    5.0    9.000000 15.000000 6.000000
#Shop C    5.5   10.000000 14.000000 7.000000