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

前端 未结 4 1326
自闭症患者
自闭症患者 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:48

    You may do this in dplyr using mutate:

    library(dplyr)
    df %>%
      group_by(group) %>%
      mutate(grp.mean.values = mean(value))
    

    ...or use data.table to assign the new column by reference (:=):

    library(data.table)
    setDT(df)[ , grp.mean.values := mean(value), by = group]
    

提交回复
热议问题