How to apply a set of functions to each group of a grouping variable in R data.frame

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-06 08:15:26

It sounds like you want to apply a set of functions to each group of a grouping variable. There are many ways to do this in R (from base R by and tapply to add-on packages like plyr, data.table, and dplyr). I've been learning how to use package dplyr, and came up with the following solution.

require(dplyr)

tab4 = tab1 %>%
    group_by(id) %>% # group by id
    mutate(value = value - min(value), value = value - lag(value)) %>% # group min to 0, difference lag 1
    na.omit %>% # remove NA caused by lag 1 differencing
    arrange(id, value) %>% # order by value within each id
    mutate(time = 1:length(value)) %>% # Make a time variable from 1 to 5 based on current order
    select(-year) # remove year column to match final OP output

Using data.table, this is simply:

require(data.table) ## 1.9.2
ans <- setDT(tab1)[, list(value=diff(value)), by=id]  ## aggregation
setkey(ans, id,value)[, time := seq_len(.N), by=id] ## order + add 'time' column

Note that your 'step 1' is unnecessary as your second step is calculating difference and it wouldn't have any effect (and is therefore skipped here).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!