How can I calculate the percentage change within a group for multiple columns in R?

后端 未结 2 604
误落风尘
误落风尘 2021-02-05 11:20

I have a data frame with an ID column, a date column (12 months for each ID), and I have 23 numeric variables. I would like to obtain the percentage change by month within each

2条回答
  •  别跟我提以往
    2021-02-05 11:36

    How about using pct <- function(x) x/lag(x)? (or (x/lag(x)-1)*100, or however you wish to specify pct change exactly) e.g.,

    pct(1:3)
    [1]  NA 2.0 1.5
    

    Edit: Adding Frank's suggestion

    pct <- function(x) {x/lag(x)}
    
    dt %>% group_by(ID) %>% mutate_each(funs(pct), c(V1, V2, V3))
    
    ID Date       V1       V2  V3
    1  Jan       NA       NA  NA
    1  Feb 1.500000 1.333333 1.2
    1  Mar 2.333333 2.000000 1.5
    2  Jan       NA       NA  NA
    2  Feb 2.000000 3.000000 4.0
    2  Mar 3.500000 2.666667 2.0
    

提交回复
热议问题