Zoo lag diff back in data frame

前端 未结 1 1263
独厮守ぢ
独厮守ぢ 2021-01-29 01:04

I want to place the results of a lagged diff back into my data frame. It means I would have leading NAs for the different lags.

I am using:

new.df$lag1         


        
相关标签:
1条回答
  • 2021-01-29 01:55
    dta = c(10,15,89,40,55,67,79)
    
    require(zoo)
    
    apply(lag(zoo(dta), c(-1,0), na.pad = TRUE), 1L, diff)
    
    #> apply(lag(zoo(dta), c(-1,0), na.pad = TRUE), 1L, diff)
    #  1   2   3   4   5   6   7 
    # NA   5  74 -49  15  12  12 
    

    Also, try to avoid naming your objects with names already used by base R (like data)!


    On May 10th 2018 it was pointed to me by @thistleknot (thanks!) that dplyr masks stats's own lag generic. Therefore make sure you don't have dplyr attached, or instead run stats::lag explicitly, otherwise my code won't run.

    I think I found the culprit: github.com/tidyverse/dplyr/issues/1586 answer: This is a natural consequence of having lots of R packages. Just be explicit and use stats::lag or dplyr::lag

    0 讨论(0)
提交回复
热议问题