[R] Coding a new variable based on criteria in a dataset

Hadley Wickham hadley at rice.edu
Thu Dec 23 02:32:12 CET 2010

>  It isn't quite convenient to read the data posted below into R
> (if it was originally tab-separated, that formatting got lost) but
> ddply from the plyr package is good for this: something like (untested)
>  d <- with(data,ddply(data,interaction(UniqueID,Reason),
>                    function(x) {
>                          ## make sure x is sorted by date/time here
>                          x$F_R <- c("F",rep("R",nrow(x)-1))
>                          x
>                     })

Or a little more succinctly:

d <- ddply(data, c("UniqueID", "Reason"), transform, F_R =


Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University

More information about the R-help mailing list