[英]R: Modifying Subsets of Dataframe using Calculations on that Subset
我將通過示例來問我的問題,因為我不知道總體上表達它的最佳方法是什么。 使用內置在R中的ChickWeight數據集:
> head(ChickWeight)
weight Time Chick Diet
1 42 0 1 1
2 51 2 1 1
3 59 4 1 1
4 64 6 1 1
5 76 8 1 1
6 93 10 1 1
> tail(ChickWeight)
weight Time Chick Diet
573 155 12 50 4
574 175 14 50 4
575 205 16 50 4
576 234 18 50 4
577 264 20 50 4
578 264 21 50 4
例如,我可以使用ddply計算每個唯一飲食的均值
> ddply(d, .(Diet), summarise, mean_weight=mean(weight, na.rm=TRUE))
Diet mean_weight
1 1 102.6455
2 2 122.6167
3 3 142.9500
4 4 135.2627
如果我想輕松創建一個數據框架以將ChickWeight中的“體重”列除以相應飲食的mean_weight,該怎么辦?
簡短,快速且可讀的data.table
解決方案:
library(data.table)
cw <- data.table(ChickWeight)
cw[, pct_mw_diet:=weight/mean(weight, na.rm=T), by=Diet]
現在,您有一個列,其中包含按飲食計算的平均體重百分比
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.