Coding a new variable based on criteria in a dataset
?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 =
c("F",rep("R",nrow(x)-1))
Hadley
Assistant Professor / Dobelman Family Junior Chair Department of Statistics / Rice University http://had.co.nz/