Calculate group mean (or other summary stats) and assign to original data

前端 未结 4 1323
自闭症患者
自闭症患者 2020-11-21 10:15

I want to calculate mean (or any other summary statistics of length one, e.g. min, max, length, sum) of a nu

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 10:42

    One option is to use plyr. ddply expects a data.frame (the first d) and returns a data.frame (the second d). Other XXply functions work in a similar way; i.e. ldply expects a list and returns a data.frame, dlply does the opposite...and so on and so forth. The second argument is the grouping variable(s). The third argument is the function we want to compute for each group.

    require(plyr)
    ddply(dat, "group", transform, grp.mean.values = mean(value))
    
      id group value grp.mean.values
    1  1     a    10              15
    2  2     a    20              15
    3  3     b   100             150
    4  4     b   200             150
    

提交回复
热议问题