Skip to navigation

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))


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.

One Response to “Nice R example from r-help”

  1. David Winsemius Says:

    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’)[!ind]) <- TRUE