我有一个数据集,我需要计算每个独特大坝的特征平均值,这是一个示例数据集:
pig <- c(20111,20112,20113,20571,20572,20573,20584,20585,20586)
sex <- c(1,1,2,2,2,2,2,1,2)
wt <- c(1.54,0.84,0.83,1.14,1.42,1.07,1.25,1.05,1.42)
dam <- c(1661,1661,1661,1027,1027,1027,10331,10331,10331)
res <-c(1,1,1,1,1,NA,1,2,1)
mt <- c(2,2,2,1,1,NA,1,1,1)
ms <- c(1,1,1,1,1,NA,1,1,1)
cr <- c(26,24,21,23,25,24,22,22,22)
rt <- c(38.7,37.2,37.8,38.1,38.4,NA,38.1,38,38.3)
data <- data.frame(pig,sex,wt,dam,res,mt,ms,cr,rt)
data
我想有这样的事情:
udam <- c(1661,1027,10331)
tpig <- c(3,3,3)
asex <- c(1.3,2,1.7)
awt <- c(1.07,1.21,1.24)
ares <- c(1,1,1.33)
amt <- c(2,1,1)
ams <- c(1,1,1)
acr <- c(23.7,24,22)
art <- c(37.6,38.25,38.1)
data2 <- data.frame(udam,tpig,asex,awt,ares,amt,ams,acr,art)
我希望我的问题很清楚,任何帮助都会受到赞赏!
Poasa
答案 0 :(得分:3)
plyr
包具有非常有用的功能来执行此操作。例如,我们可以使用ddply
按因子拆分数据框,应用函数,然后在数据框中再次返回结果:
library('plyr')
ddply(data,.(dam),mean,na.rm=T)
pig sex wt dam res mt ms cr rt
1 20572 2.000000 1.21 1027 1.000000 1 1 24.00000 38.25000
2 20112 1.333333 1.07 1661 1.000000 2 1 23.66667 37.90000
3 20585 1.666667 1.24 10331 1.333333 1 1 22.00000 38.13333
或使用summarize
功能进行更多控制:
ddply(data,.(dam),summarize,
tpig = 3,
asex = mean(sex,na.rm=T),
sexRatio = sum(sex==1)/sum(sex==2),
awt = mean(wt,na.rm=T),
ares = mean(res,na.rm=T),
amt = mean(mt,na.rm=T),
ams = mean(ms,na.rm=T),
acr = mean(cr,na.rm=T),
art = mean(rt,na.rm=T),
count = length(pig))
dam tpig asex sexRatio awt ares amt ams acr art count
1 1027 3 2.000000 0.0 1.21 1.000000 1 1 24.00000 38.25000 3
2 1661 3 1.333333 2.0 1.07 1.000000 2 1 23.66667 37.90000 3
3 10331 3 1.666667 0.5 1.24 1.333333 1 1 22.00000 38.13333 3
答案 1 :(得分:1)
此:
aggregate(cbind(sex, wt, res, mt, ms, cr, rt) ~ dam, data=data, FUN=mean,
na.rm=TRUE, na.action=na.pass)
应该为平均值做的伎俩。我假设您想要从受影响变量的均值中排除NA,但不包括观察结果。可以使用
获得计数aggregate(pig ~ dam, data=data, FUN=length)