Sunday, 15 January 2012

grouping - R: creating sequence of numbers by group and starting the sequence by a particular condition -



grouping - R: creating sequence of numbers by group and starting the sequence by a particular condition -

i create new variable, number, sequentially generate numbers within grouping id, starting @ particular status (in case, when percent > 5).

groupid <- c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3) percent <- c( 3, 4, 5, 10, 2, 1, 6, 8, 4, 8, 10, 11) number <- ifelse (percent < 5, 0, 1:4)

i get:

> number [1] 0 0 3 4 0 0 3 4 0 2 3 4

but i'd like:

0 0 1 2 0 0 1 2 0 1 2 3

i did not include groupid variable within ifelse statement , used 1:4 instead, there 4 rows within each groupid.

any suggestions or clues? give thanks you!

it's ugly , throws warnings, gets want:

ave(percent,groupid,fun=function(x) {x[x<5] <- 0; x[x>=5] <- 1:4; x} ) #[1] 0 0 1 2 0 0 1 2 0 1 2 3

@bondeddust's reply below using cumsum more appropriate though.

if info not in ascending order in each group, replace >=5 values like:

percent <- c( 3, 5, 4, 10, 2, 1, 6, 8, 4, 8, 10, 11) ave(percent, list(groupid,percent>=5), fun=function(x) cumsum(x>=5)) #[1] 0 1 0 2 0 0 1 2 0 1 2 3

r grouping sequence

No comments:

Post a Comment