How to calculate percentage change from different rows over different spans

前端 未结 2 659
孤街浪徒
孤街浪徒 2021-01-15 18:33

I am trying to calculate the percentage change in price for quarterly data of companies recognized by a gvkey(1001, 1384, etc...). and it\'s corresponding quart

2条回答
  •  臣服心动
    2021-01-15 19:16

    df <- read.table(text="gvkey  PRCCQ
    1  1004  5.500
    2  1004  4.450
    3  1004  4.500
    4  1004  8.010
    5  1005  4.450
    6  1005  4.500",header=TRUE)
    
    library(plyr)
    library(quantmod)
    ddply(df, "gvkey", transform, DeltaCol = Delt(PRCCQ,k=3))
    #error
    
    Delt2 <- function(x,k) {
      if(length(x)>k) as.vector(Delt(x1=x,k=k)) else rep(NA,length(x))
    }
    
    ddply(df, "gvkey", transform, DeltaCol = Delt2(PRCCQ,k=3))
    #  gvkey PRCCQ  DeltaCol
    #1  1004  5.50        NA
    #2  1004  4.45        NA
    #3  1004  4.50        NA
    #4  1004  8.01 0.4563636
    #5  1005  4.45        NA
    #6  1005  4.50        NA
    

提交回复
热议问题