0

Possible Duplicate:
Basic lag in R vector/dataframe

Trying to lag a variable in R but it isn't working.

x<-1:10
y=lag(x,1)
xy=cbind(x,y)
View(xy)

    x   y
1   1   1
2   2   2
3   3   3
4   4   4
5   5   5
6   6   6
7   7   7
8   8   8
9   9   9
10  10  10

I am still not getting the lag. What am I doing wrong? Also is there a quicker way to combine to vectors/matrices without using cbind/rbind? For example

x=0:10
y=20:30
newxy=[x,y]

Thank you!

Community
  • 1
  • 1
gabriel
  • 399
  • 2
  • 7
  • 17

3 Answers3

2

lag() expects a time series. (In R, class "ts" is the basic time-series class, used to represent data sampled at equispaced points in time. For more see ?ts.) So you can either convert x to a time-series, as demonstrated here, or make use one of the approaches suggested in another answer.

x <- as.ts(1:10)
y <- lag(x,1)
xy <- cbind(x,y)
xy
#Time Series:
#Start = 0 
#End = 10 
#Frequency = 1 
#    x  y
# 0 NA  1
# 1  1  2
# 2  2  3
# 3  3  4
# 4  4  5
# 5  5  6
# 6  6  7
# 7  7  8
# 8  8  9
# 9  9 10
#10 10 NA
MattBagg
  • 10,268
  • 3
  • 40
  • 47
2

For the second part:

newxy=matrix(c(x,y),ncol=2)

> newxy
      [,1] [,2]
 [1,]    0   20
 [2,]    1   21
 [3,]    2   22
 [4,]    3   23
 [5,]    4   24
 [6,]    5   25
 [7,]    6   26
 [8,]    7   27
 [9,]    8   28
[10,]    9   29
[11,]   10   30
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
2

embed is a useful function here, especially if you don't want to convert to a ts object.

x <- 1:10
embed(x,2)


     [,1] [,2]
 [1,]    2    1
 [2,]    3    2
 [3,]    4    3
 [4,]    5    4
 [5,]    6    5
 [6,]    7    6
 [7,]    8    7
 [8,]    9    8
 [9,]   10    9
mnel
  • 113,303
  • 27
  • 265
  • 254