按因子变量在数据框中进行Colmeans

时间:2015-05-11 13:38:08

标签: r dataframe data.table plyr

我试图在不同因素的数据框中得到一些变量的均值。说我有:

    time    geo var1    var2   var3    var4
1   1990    AT  1       7      13       19
2   1991    AT  2       8      14       20
3   1992    AT  3       9      15       21
4   1990    DE  4       10     16       22
5   1991    DE  5       11     17       23
6   1992    DE  6       12     18       24

我想要:

    time    geo var1    var2   var3    var4   m_var2   m_var3
1   1990    AT  1       7      13       19    8        14
2   1991    AT  2       8      14       20    8        14
3   1992    AT  3       9      15       21    8        14
4   1990    DE  4       10     16       22    11       17
5   1991    DE  5       11     17       23    11       17
6   1992    DE  6       12     18       24    11       17

我用by()和lapply()尝试过一些东西,但我认为这是ddply的方向

require(plyr)
Dataset <- data.frame(time=rep(c(1990:1992),2),geo=c(rep("AT",3),rep("DE",3))
      ,var1=as.numeric(c(1:6)),var2=as.numeric(c(7:12)),var3=as.numeric(c(13:18)),
      var4=as.numeric(c(19:24)))

newvars <- c("var2","var3")
newData <- Dataset[,c("geo",newvars)]

目前,我可以选择两个错误:

ddply(newData,newData[,"geo"],colMeans) 
#where R apparently thinks AT is the variable?

ddply(newData,"geo",colMeans)
#where R worries about the factor variable not being numeric?

我的lapply尝试让我走得很远,但后来给我留下了一个我无法回到数据框的列表:

lapply(newvars,function(x){
       by(Dataset[x],Dataset[,"geo"],function(x) 
       rep(colMeans(x,na.rm=T),length(unique(Dataset[,"time"]))))
       })

我认为这必须能够使用合并和过滤器,如下所示: Lapply in a dataframe over different variables using filters,但我无法将它们结合在一起。任何帮助将不胜感激!

4 个答案:

答案 0 :(得分:7)

dplyr

的其他方法
library(dplyr)
df1 %>% group_by(geo) %>% mutate(m_var2=mean(var2), m_var3=mean(var3))

答案 1 :(得分:7)

另一个简单的基础R解决方案就是

transform(df, m_var2 = ave(var2, geo), m_var3 = ave(var3, geo))
#   time geo var1 var2 var3 var4 m_var2 m_var3
# 1 1990  AT    1    7   13   19      8     14
# 2 1991  AT    2    8   14   20      8     14
# 3 1992  AT    3    9   15   21      8     14
# 4 1990  DE    4   10   16   22     11     17
# 5 1991  DE    5   11   17   23     11     17
# 6 1992  DE    6   12   18   24     11     17

几年后,我认为更简洁的方法是更新实际数据集(而不是创建新数据集)并对列向量进行操作(而不是手动编写)

vars <- paste0("var", 2:3) # Select desired cols
df[paste0("m_", vars)] <- lapply(df[vars], ave, df[["geo"]]) # Loop and update

答案 2 :(得分:5)

一种选择是使用data.table。我们可以将data.frame转换为data.tablesetDT(df1)),获取所选列的meanlapply(.SD, mean))(&#39; var2&#39;和&#39; var3&#39;)通过在.SDcols中指定列索引,按&#39; geo&#39;分组。通过将输出(:=)分配给新列名称(paste('m', names(df1)[4:5]))来创建新列

library(data.table)
setDT(df1)[, paste('m', names(df1)[4:5], sep="_") :=lapply(.SD, mean)
            ,by = geo, .SDcols=4:5]
#     time geo var1 var2 var3 var4 m_var2 m_var3
#1: 1990  AT    1    7   13   19      8     14
#2: 1991  AT    2    8   14   20      8     14
#3: 1992  AT    3    9   15   21      8     14
#4: 1990  DE    4   10   16   22     11     17
#5: 1991  DE    5   11   17   23     11     17
#6: 1992  DE    6   12   18   24     11     17

注意:此方法更为通用。我们甚至可以为100个变量创建mean列,而不会对代码进行任何重大更改。即。如果我们需要获取第4:100列的mean,请更改.SDcols=4:100paste('m', names(df1)[4:100]

数据

df1 <- structure(list(time = c(1990L, 1991L, 1992L, 1990L, 1991L, 1992L
), geo = c("AT", "AT", "AT", "DE", "DE", "DE"), var1 = 1:6, var2 = 7:12, 
var3 = 13:18, var4 = 19:24), .Names = c("time", "geo", "var1", 
"var2", "var3", "var4"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))

答案 3 :(得分:4)

base R:

 cbind(df1,m_var2=ave(df1$var2,df1$geo),m_var3=ave(df1$var3,df1$geo))