使用多个不同的group_by变量(dplyr)来汇总数据帧

时间:2016-05-20 13:48:16

标签: r dplyr

我有一个数据框“my_data”,其中包含6列:

group1.members  group2.members  group3.members  price    price.2   price.3
 1                 1               1             800      877      334
 1                 2               1             850      877      334
 2                 2               1             859      877      334
 3                 1               1             859      877      334
 3                 1               2             870      877      334
 2                 2               2             870      877      334
 2                 3               2             870      877      334
 1                 3               3             880      877      334

我想通过ROW总结my_data的“价格”列到几个单独的数据框中,在每个不同的“group.member”列上使用group_by。看来,group_by不允许这样做?

这就是我的想法:

my_data <- as.data.frame(data)
num_of_years <- c(1,2,3)
for(i in 1:length(num_of_years)){
   price_means <- my_data %>% group_by(my_data[i]) %>% 
   select(-value) %>%
   summarise_each(funs(mean(., na.rm=TRUE))) %>% 
   ungroup
   assign(paste("PriceMeans",i,sep=""),price_means, envir = .GlobalEnv)
}

换句话说:

  • 对于i = 1,请使用group_by(group1.members)
  • for i = 2,使用group_by(group2.members)
  • for i = 3,使用group_by(group3.members)

编辑:我的解决方案:

for(i in 1:length(my_groups)){ 
  # construct the group to select
  current.group <- my_groups[i] 
  current.group <- paste0("memb_", current.group) 
  # construct the groups to exclude
  groups.to.drop <- my_groups[-i] 
  groups.to.drop <- paste0("memb_", groups.to.drop) 

  # Get Means 
  Means <- data %>% group_by_(as.name(current.group)) %>%  
    select(- c(ID, get(groups.to.drop))) %>% 
    summarise_each(funs(mean(., na.rm = TRUE))) 
  Means <- Means[,-1:-(length(my_groups)-1)] 
  Means <- as.list(Means) 
  assign(x = paste0("Means_",i), 
         value = Means,  
         envir = parent.env(new.env()) 
}

1 个答案:

答案 0 :(得分:1)

我绝不是dplyr专家,但这似乎完成了你想要做的事情:

for (i in 1:length(num_of_years)){
  var1 <- names(my_data)[[i]]
  var2 <- c(var1)

  price_means <- my_data %>% 
    select(eval(i), price, price.2, price.3) %>% 
    group_by_(var2) %>% 
    summarise_each(funs(mean(., na.rm=TRUE))) %>% 
    ungroup()

  assign(paste("PriceMeans",i,sep=""),price_means, envir = .GlobalEnv)
}