R Add previous month value as a column

后端 未结 2 1238
梦如初夏
梦如初夏 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)
    

提交回复
热议问题