Nice R example from r-help
I don’t know the first thing about programming, but sometimes you see something and appreciate how elegant it is. This small solution from r-help is a good example. Someone wanted, given a vector c('p','p','t','t','t','p','k','t') to produce NA NA 1 2 3
test <- c('p','p','t','t','t','p','k','t')
v <- cumsum(ind <- test == 't')
v[!ind] <- NA
I didn't know you could assign something to an object and use it at the same time. Very neat. So if you wanted this all at once, you could also do:
v <- ifelse(cumsum(ind <- test=='t')==0,NA,cumsum(ind))
or
ifelse((v <- cumsum(test=='t'))==0,NA,v)
Maybe Dimitris' solution is in fact preferred for R, using indexing instead of if/ else, but I don't know enough about R to know whether that makes a difference.
December 12th, 2009 at 17:26
The ifelse function will sometimes return vectors of a different class than the consequent arguments, so a method that sets elements to NA “in place” is safer. Also possible (but less intuitive) is:
test <- c(‘p’,'p’,'t’,'t’,'t’,'p’,'k’,'t’)
v <- cumsum(ind <- test == ‘t’)
is.na(v[!ind]) <- TRUE
v
–
David