[R] lag variable addition to data frame question

Austin, Matt maustin at amgen.com
Fri Oct 29 17:14:29 CEST 2004


?diff

--Matt

-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch]On Behalf Of s viswanath
Sent: Friday, October 29, 2004 7:22 AM
To: r-help at stat.math.ethz.ch
Subject: [R] lag variable addition to data frame question


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

______________________________________________
R-help at stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide!
http://www.R-project.org/posting-guide.html




More information about the R-help mailing list