Skip to content
Prev 1815 / 7420 Next

change values of a vector selectively

What about something along that line? It implies converting into numeric
and then back to factor to take benefit of each class:

(bli <- factor(c(1, 0,0,0,0,0, 2,0,0,0,0,0, "A", 0,0,0,0,2, 0,0,0,1)))

blo <- ifelse(bli != 0, as.numeric(bli), 0)

bla <- factor(cumsum(blo))
levels(bla) <- bli[bli != 0]
bla

You can remove the 'blo' step and doing the whole stuff in one line
(factor(cumsum(ifelse(...)))), but I thought it was easier to understand
that way. I haven't tested on a large dataset if it's more efficient
than the 'for' approach, though.

Hope this helps,
Mathieu.


Le 2011-01-11 09:58, B.-Markus Schuller a ?crit :