[R] Can you have a by variable in Lag function as in SAS

Nordlund, Dan (DSHS/RDA) NordlDJ at dshs.wa.gov
Fri Nov 16 00:01:43 CET 2012


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of ramoss
> Sent: Thursday, November 15, 2012 11:56 AM
> To: r-help at 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




More information about the R-help mailing list