Wookeun Lee Wookeun Lee - 1 year ago 86
R Question

How do I lag a data.frame?

I'd like to lag whole dataframe in R.

In python, it's very easy to do this, using

shift()
function
(ex:
df.shift(1)
)

However, I could not find any as an easy and simple method as in pandas
shift()
in R.

How can I do this?

> x = data.frame(a=c(1,2,3),b=c(4,5,6))
> x
a b
1 1 4
2 2 5
3 3 6


What I want is,

> lag(x,1)
>
a b
1 NA NA
2 1 4
3 2 5


Any good idea?

Answer Source
library(dplyr)
x %>% mutate_all(lag)

   a  b
1 NA NA
2  1  4
3  2  5
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download