Calculate Percentage Change in R using dplyr

前端 未结 2 1537
独厮守ぢ
独厮守ぢ 2021-02-04 19:20

I want to calculate the percentage of Profit by YEAR which is a fairly simple task but somehow I am getting NA. I have checked same questi

2条回答
  •  南笙
    南笙 (楼主)
    2021-02-04 19:46

    Assuming that your Profit column represents the profit in a given year, this function will calculate the difference between year n and year n-1, divide by the value of year n-1, and multiply by 100 to get a percentage. If the value in year n-1 was zero, there is no valid percent change. It is important that you group the data only by VERTICAL and not by YEAR as well.

    profit_pct_change <- function(x) {
      x <- x[order(x$YEAR, decreasing = TRUE), ] # Confirms ordered by decreasing year
      pct_change <- -diff(x$Profit)/x$Profit[-1] * 100 # Gets percent change in profit from preceding year
      data.frame(year = x$YEAR[-length(x$YEAR)], pct_change = pct_change) # Returns data frame
    }
    
    df_vertical_growth %>% 
      group_by(VERTICAL) %>%
      do(profit_pct_change(.))
    

提交回复
热议问题