2011-03-10 27 views
0

我有需要計算每個唯一壩的性狀平均的數據集,這是一個例子的數據集計算每個唯一動​​物的性狀平均在一個數據集:,使用R

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

回答

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 
+0

這真的太棒了!你甚至增加了一段時間以來一直在我心中的性別比例。再次感謝你,歡呼! – baz 2011-03-10 04:12:37

1

此:

aggregate(cbind(sex, wt, res, mt, ms, cr, rt) ~ dam, data=data, FUN=mean, 
    na.rm=TRUE, na.action=na.pass) 

應該做的平均值的伎倆。我假設你想從受影響變量的手段中排除NAs,但是否則包括觀察。計數可以通過

aggregate(pig ~ dam, data=data, FUN=length)