Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:使用对数据帧子集的计算修改该子集_R_Statistics - Fatal编程技术网

R:使用对数据帧子集的计算修改该子集

R:使用对数据帧子集的计算修改该子集,r,statistics,R,Statistics,我将通过一个例子来问我的问题,因为我不知道用什么样的方式来表达它。使用内置于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

我将通过一个例子来问我的问题,因为我不知道用什么样的方式来表达它。使用内置于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中的“重量”列,我该怎么办?

一个包含
数据的解决方案。表格
简短、快速且可读:

library(data.table)
cw <- data.table(ChickWeight)
cw[, pct_mw_diet:=weight/mean(weight, na.rm=T), by=Diet]
库(data.table)

cw可能是你在找这个<代码>库(dplyr);雏鸡体重%>%分组依据(饮食)%>%变异(体重=体重/平均值(体重,na.rm=TRUE))
或由于您使用的是
plyr
ddply(d,(饮食),转换,w_体重=体重/平均值(体重,na.rm=TRUE))
谢谢。这两个都起作用了,只是因为某种原因找不到它们