[R] comparing with lead function

hadley wickham h.wickham at gmail.com
Wed Oct 15 14:45:16 CEST 2008

On Wed, Oct 15, 2008 at 5:59 AM, Michael Pearmain <mpearmain at google.com> wrote:
> Hi All,
> I've been trying to compare if the previous value in a variable is equal to
> a binary value..(i.e i want to check if the last event was a yes or no)
> i've been trying to write some code for this, but it seems overly elaborate,
> can anyone suggest a better / shorter / neater way?
> The below doesn't quite work but shows my idea of splitting by the factor
> id, then creating a new vector that is lead, then i was going to use an
> ifelse clause..
> But as i suggested this seem very elaborate.. my sample code below

How about:

ddply(DF, .(id), transform, diff = c(NA, tail(time, -1)))

This splits the data frame up by id, transforms each piece in the same
way as your code (but expressed a little more elegantly) and then
joins the pieces back together.

More info about plyr is available at http://had.co.nz/plyr




More information about the R-help mailing list