Alex Rivera | Logout

Compute counting variable in dataframe

Asked 2012-10-29T09:26:39.737
8

I have an R data frame:

a <- 1:12  
list <- c(rep("x",3),rep("y",4),rep("z",3),rep("x",2))  
data <- data.frame(a,list)

data  
 a list  
 1    x  
 2    x  
 3    x  
 4    y  
 5    y  
 6    y  
 7    y  
 8    z  
 9    z  
10    z  
11    x  
12    x

I want to create a new column which begins counting at 1 every time the value of "list" changes, i.e. in this example:

b <- c(1:3,1:4,1:3,1:2)    
data <- data.frame(a,list,b)  

I am far from being an expert in R and cannot for the life of me work out an efficient way of doing this. My main problem seems to be that any value of "list" can come back at any time, but there is no rule to the length of the blocks of one value. Does anyone have any ideas? Thanks!

r
Edit
Report

1 Answer

5

The key idea is to use rle() (run length encoding) on data$list (after coercing it to an atomic vector - after all, we are not interested in the specific entries). Then we use seq() to create sequences starting at 1 and ending at the calculated run length. Finally, we paste all these sequences together:

unlist(lapply(rle(as.numeric(data$list))$lengths,FUN=seq,from=1))
answered 2012-10-29T09:41:24.043

Your Answer