Calculating %changes with the By()

后端 未结 3 1530
一生所求
一生所求 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:31

    Since the OP specifically asked about using by() I thought I'd provide an answer the illustrates it's use.

    First you write a function that acts on each 'piece' of the data frame:

    myFun <- function(x){
    n <- nrow(x)
    x$Change <- c(NA,diff(x$Temp) / head(x$Temp,n-1))
    x
    }
    

    I've used the base functions diff to calculate the sequential differences in Temp and then since the resulting vector has length n-1, we use head to divide the the differences by all but the last Temp value. (I did this just to work head in since it's handy; there are lots of other ways to do that).

    Then the by call:

    by(dat,dat$ID,FUN=myFun)
    

    If you want to put all the pieces back together again, we can use do.call and rbind:

    do.call(rbind,by(dat,dat$ID,FUN=myFun))
    

提交回复
热议问题