0

So let's say I have a data frame df that has 3 columns:

x   y   z
----------
1  0.2  yes
2  7.1  no
3  2.4  no
4  1.1  yes
5  6.0  no

I would like to add to df two new variables/columns "last.y" and "last.z", which would basically store the previous value (if there is a previous row) of "y" and "z" to the current row in a following way:

x   y   z   last.y   last.z
---------------------------
1  0.2  yes  NA       NA
2  7.1  no   0.2      yes   
3  2.4  no   7.1      no
4  1.1  yes  2.4      no
5  6.0  no   1.1      yes

How can I do this in R? Thanks in advance!

rjuri
  • 133
  • 7

1 Answers1

1

You can use dplyr::lag() in mutate to get the new columns:

df %>%
  mutate(last.y = dplyr::lag(y),
         lazt.z = dplyr::lag(z))

Output:

  x   y   z last.y lazt.z
1 1 0.2 yes     NA   <NA>
2 2 7.1  no    0.2    yes
3 3 2.4  no    7.1     no
4 4 1.1 yes    2.4     no
5 5 6.0  no    1.1    yes

Data

df <- data.frame(x = 1:5,
                 y = c(0.2, 7.1, 2.4, 1.1, 6.0),
                 z = c("yes","no","no","yes", "no"))
jpsmith
  • 11,023
  • 5
  • 15
  • 36