R Add previous month value as a column

后端 未结 2 1237
梦如初夏
梦如初夏 2021-01-21 04:17

I have a data table with date and price by month:

set.seed(128)
dat <- data.table(DATE=c(\"2014-01-01\",\"2014-02-01\",\"2014-03-01\",\"2014-04-01\",
                 


        
相关标签:
2条回答
  • 2021-01-21 04:53

    The first term has no known price for previous month (I'm assuming - if it does, you can replace the NA with it).

    The following code should work fine. The first line creates a new vector, the second adds it as a column to dat and the third removes the vector (as it's now in dat and we don't need it separately).

    PRICE_PREV <- c(NA, dat$PRICE[1:length(dat$PRICE)-1])
    dat <- cbind(dat, PRICE_PREV)
    rm(PRICE_PREV)
    
    0 讨论(0)
  • 2021-01-21 04:56

    Use shift from data.table v >= 1.9.5 (on GitHub)

    dat[, PRICE_PREV := shift(PRICE)]
    dat
    #           DATE     PRICE PRICE_PREV
    #  1: 2014-01-01 108.95158         NA
    #  2: 2014-02-01 107.23918  108.95158
    #  3: 2014-03-01 124.96608  107.23918
    #  4: 2014-04-01  99.61007  124.96608
    #  5: 2014-05-01 118.13540   99.61007
    #  6: 2014-06-01 108.70528  118.13540
    #  7: 2014-07-01  93.12482  108.70528
    #  8: 2014-08-01 100.06829   93.12482
    #  9: 2014-09-01 103.14932  100.06829
    # 10: 2014-10-01 122.66710  103.14932
    # 11: 2014-11-01 104.84064  122.66710
    # 12: 2014-12-01 113.37610  104.84064
    

    If you have an older version (v < 1.9.5) you could also do

    dat[, PRICE_PREV := c(NA, PRICE[-.N])]
    
    0 讨论(0)
提交回复
热议问题