'How to create new data using function in time series data in R?

hi everyone i have time series data like this:

  Time                Price          
  <dttm>              <dbl>          
1 2018-02-21 09:00:00  122.0 
2 2018-02-21 09:07:38  122.1 
3 2018-02-21 09:09:10  122.0 
4 2018-02-21 09:09:10  123.0 
5 2018-02-21 09:09:21  122.1 
6 2018-02-21 09:13:16  121.2 

and i want to create new data using this function: let pt=current price , pt-1 =previous price R = ln(pt-pt-1)*100 Thank you



Solution 1:[1]

You can use dplyr::lag. Careful, however, because the log of a negative value is undefined, so you get a bunch of NaN values. This may not be what you're looking for.

dat %>% 
  mutate(Time = ymd_hms(Time),
         lagPrice = lag(Price, default = first(Price)),
         R = log(Price - lagPrice) * 100)

                 Time Price lagPrice         R
1 2018-02-21 09:00:00 122.0    122.0      -Inf
2 2018-02-21 09:07:38 122.1    122.0 -230.2585
3 2018-02-21 09:09:10 122.0    122.1       NaN
4 2018-02-21 09:09:10 123.0    122.0    0.0000
5 2018-02-21 09:09:21 122.1    123.0       NaN
6 2018-02-21 09:13:16 121.2    122.1       NaN

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maël