Calculating %changes with the By()

后端 未结 3 1525
一生所求
一生所求 2021-01-05 08:20

I am an inexperienced R user and have been struggling with the By() function and would appreciate your help. The task is simple, I have a longitudinal dataset (How do I decl

3条回答
  •  死守一世寂寞
    2021-01-05 08:41

    Your suggested output is not "%change" (but rather fractional difference) while this illustrates a method getting "percent of original" using the initial value as the basis for the change:

    > dat$pctTemp <-  unlist(
                tapply(dat$Temp, dat$ID, function(x) c(NA, 100*x[-1]/x[1]) )
                            )
    > dat
        ID     Date      Temp   pctTemp
    1  AAA 1/1/2003 0.7498817        NA
    2  AAA 1/2/2003 0.6666616  88.90223
    3  AAA 1/3/2003 0.7730799 103.09358
    4  AAA 1/4/2003 0.6290236  83.88305
    5  AAA 1/5/2003 0.7333124  97.79041
    6  BBB 1/1/2003 0.7073398        NA
    7  BBB 1/2/2003 0.7649865 108.14980
    8  BBB 1/3/2003 0.6622015  93.61858
    snipped
    

    If you want interval change, you can divide diff(x) by the prceding values

    > dat$pctTemp <-  unlist(tapply(dat$Temp, dat$ID, function(x) c(NA, 100*diff(x)/x[-length(x)]) )  )
    > dat
        ID     Date      Temp      pctTemp
    1  AAA 1/1/2003 0.7498817           NA
    2  AAA 1/2/2003 0.6666616 -11.09776868
    3  AAA 1/3/2003 0.7730799  15.96287574
    4  AAA 1/4/2003 0.6290236 -18.63407501
    5  AAA 1/5/2003 0.7333124  16.57946178
    6  BBB 1/1/2003 0.7073398           NA
    7  BBB 1/2/2003 0.7649865   8.14979813
    snipped
    

提交回复
热议问题