将数据列除以组 [英] Divide column of data by mean of the group

查看:82
本文介绍了将数据列除以组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有数据框,例如:

If I have a data frame, such as:

group=rep(1:4,each=10)
data=c(seq(1,10,1),seq(5,50,5),seq(20,11,-1),seq(0.3,3,0.3))
DF=data.frame(group,data)

现在,我想将每个data元素除以其组的均值.例如:

Now, I would like to divide each data element by the mean of its group. For example:

group=rep(1:4,each=10)
data=c(seq(1,10,1),seq(5,50,5),seq(20,11,-1),seq(0.3,3,0.3))
DF=data.frame(group,data)
aggregate(DF,by=list(DF$group),FUN=mean)

#Group.1 group  data
#1       1     1  5.50
#2       2     2 27.50
#3       3     3 15.50
#4       4     4  1.65

data1=c(seq(1,10,1)/5.5,seq(5,50,5)/27.5,seq(20,11,-1)/15.5,seq(0.3,3,0.3)/1.65)
DF1=data.frame(group, data1)

但是,这有点令人费解,并且在大型数据集中工作不容易.我觉得这里有一个apply应用程序可以使用,但是我找不到找到它的好方法.

However, this is a bit convoluted, and work not work easily in a large dataset. I feel like there is an apply application which could be used here, but I cannot find a nice way to do it.

推荐答案

以下是常用的选项集(感谢@ G.Grothendieck简化了ave):

Here's the usual set of options (thanks to @G.Grothendieck for simplification of ave):

# base R 
DF$newdata = ave(DF$data, DF$group, FUN = function(x) x/mean(x))
# or...
DF$newdata = DF$data / ave(DF$data, DF$group)

# dplyr
library(dplyr)
DF %>% group_by(group) %>% mutate(newdata = data/mean(data))

# data.table
library(data.table)
setDT(DF)[, newdata := data/mean(data), by=group]

这篇关于将数据列除以组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆