[R] lag variable addition to data frame question

s viswanath ru68y7s at myrealbox.com
Fri Oct 29 16:21:55 CEST 2004


Hi,

I was wondering if there is a more efficient way of handling the following method of creating a lagged value in a data frame without using the recursive 
'for(i in 1:n)' loop and without using as.ts

#Steps to creating a lag variable in a data frame 'my.dat.fr'
# with 275 columns, 2400 rows of numbers and factors . The #variable x is a factor of #with five different levels
the way i am creating the variable now is:

attach(my.dat.fr)
#my.dat.fr contains a variable 'x', i want to create #lagged variables #of this without using as.ts(). Is #there a more effient way of doing this than#below and #without using a recursive loop  such as 
#for( i in 1:obs)x.lag[i]= x[(i-1)]

1.here is the way i am doing the lag now
x=c(3,2,3,2,1,1,1,2,1,2,1,3...1)

obs=length(x)

x.nolag=x[2:obs]
x.lag1=x[1:(obs-1)]

my.new=cbind(x.nolag,x.lag1)

#since my data frame must line up my orginal x values to other columns I also # add the following


x.fill= cbind(0,0)
# as named the above cell lines up my factor to other factors in my data frame, #since I had chopped off the first x observation to create x above (ie x[2:obs]) #then finally

my.dat.fr=rbind(x.fill, my.new)
my.dat.fr

#Is there a easier way to create a lag variable and install in my data frame?
#thankyou in advance, Sri




More information about the R-help mailing list