简体   繁体   English

如何在R中拆分应用合并几个变量/列

[英]How to Split-Apply-Combine for several variables / columns in R

I'd like to perform a function on several variables, by group. 我想按组对几个变量执行功能。

Fake data; 伪数据;

df<-data.frame(rnorm(100,mean=10), 
               rnorm(100,mean=15),
               rnorm(100,mean=20),
               rep(letters[1:10],each=10)
               )
colnames(df)<-c("var1","var2","var3","group1")

In this particular case, I'd like to mean-center each variable by group. 在这种情况下,我想将每个变量按组居中。 I want to return a dataframe with the original and centered variables. 我想返回一个带有原始变量和居中变量的数据框。

Normally I use PLYR package for this; 通常我为此使用PLYR包;

library(plyr)    
ddply(df, "group1", transform, centered_var1= scale(var1, scale=FALSE))

However, I haven't been able to successfully loop this function, or think of another minimal-code way to do this. 但是,我无法成功地循环执行此功能,也无法想到实现此目的的另一种最小代码方式。

I'm open to non-PLYR solutions...My main criteria is keeping code to a minimum. 我对非PLYR解决方案持开放态度...我的主要标准是将代码保持在最低限度。

Using dplyr 使用dplyr

library(dplyr)
df %>% group_by(group1) %>%
  mutate_each(funs(scale(., scale=F))) -> res

The colwise function may be what you're looking for. colwise函数可能就是您想要的。

library("plyr")
ddply(df, .(group1), colwise(scale, scale = FALSE))

Is this what you want? 这是你想要的吗?

ddply(df, "group1", transform, centered_var1= scale(var1, scale=FALSE),
      centered_var2 = scale(var2, scale=FALSE),
      centered_var3 = scale(var3, scale=FALSE))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM