> -----Original Message----- > From: r-help-boun...@r-project.org [mailto:r-help-bounces@r- > project.org] On Behalf Of ramoss > Sent: Thursday, November 15, 2012 11:56 AM > To: r-help@r-project.org > Subject: [R] Can you have a by variable in Lag function as in SAS > > Hello, > > I want to use lag on a time variable but I have to take date into > consideration ie I don't want days to overlap ie: > I don't want my first time of today to match my last time of yeterday. > > In SAS I would use : > > data x; > set y; > by date tim; > previous=lag(tim); > if first.date then > do; > previous=.; > end; > run; > > How can I do something similar in R? I can't find any examples > anywhere. > > Thank you all for your help. > >
I haven't seen a response to this question yet, so here is an approach that may work for you. Let's say you have a data frame called dat that contains your variables date and tim. Then using the Lag() function from the Hmisc package you could do something like this library(Hmisc) dat$previous <- ave(dat$tim,dat$date,FUN=Lag) Hope this is helpful, Dan Daniel J. Nordlund Washington State Department of Social and Health Services Planning, Performance, and Accountability Research and Data Analysis Division Olympia, WA 98504-5204 ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.