Error when usuing diff() function


Hi, I am trying to use diff() to difference my price variable for stationarity. I have tried the code in the picture and also:

elecPriceData = elecPriceData %>%
mutate(diff_Price <- diff(Price_MW.h))
head(elecPriceData)

but nothing seems to work. Is there a way to only add NA to the first entry and then have my values from diff() in the remaining?

Thanks for your time!

You could use the lag() function from dplyr.

library(dplyr, warn.conflicts = FALSE)
#> Warning: package 'dplyr' was built under R version 3.6.3

mtcars %>% 
  mutate(diff_mpg = mpg - lag(mpg)) %>% 
  select(mpg, diff_mpg)
#>     mpg diff_mpg
#> 1  21.0       NA
#> 2  21.0      0.0
#> 3  22.8      1.8
#> 4  21.4     -1.4
#> 5  18.7     -2.7
#> 6  18.1     -0.6
#> 7  14.3     -3.8
#> 8  24.4     10.1
#> 9  22.8     -1.6
#> 10 19.2     -3.6
#> 11 17.8     -1.4
#> 12 16.4     -1.4
#> 13 17.3      0.9
#> 14 15.2     -2.1
#> 15 10.4     -4.8
#> 16 10.4      0.0
#> 17 14.7      4.3
#> 18 32.4     17.7
#> 19 30.4     -2.0
#> 20 33.9      3.5
#> 21 21.5    -12.4
#> 22 15.5     -6.0
#> 23 15.2     -0.3
#> 24 13.3     -1.9
#> 25 19.2      5.9
#> 26 27.3      8.1
#> 27 26.0     -1.3
#> 28 30.4      4.4
#> 29 15.8    -14.6
#> 30 19.7      3.9
#> 31 15.0     -4.7
#> 32 21.4      6.4

Created on 2020-03-30 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.