Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Perform arithmetic operation with variables at t and t-1 (R)

I want to perform the following mathematical operation between two variables at different time periods of the same dataframe:

lag_var = var1(t)/var2(t-1)

> df

var1   var2    lag_var
1       10       NA
3       12       0.3
1       16       0.083
6       19       0.375
16       7       0.84

Any ideas?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can achieve that via the lag() function and mutate, e.g.

library(dplyr)     
df %>%  mutate(lag_var = var1 / dplyr::lag(var2))

Data:

df <- read.table(text = "var1   var2    lag_var
1       10       NA
3       12       0.3
1       16       0.083
6       19       0.375
16       7       0.84", h = T)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading