Reputation: 370
I have a matrix in which I have repeated numbers in a number of columns, then the number changes and repeats in another number of columns (probably different) and that happens in the different rows. For example:
X = data.frame(replicate(10,sample(0:2,10,rep=TRUE)))
X[1:3,]
X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
1 0 2 1 0 0 0 1 1 1 1
2 1 0 1 2 0 0 1 2 2 0
3 0 2 0 1 1 0 1 1 0 1
What I want to do is create a list that contains the number of times the first number was repeated, the number of times the second number was repeated, etc. for all rows. From the example above it would be:
1 1 1 3 4
1 1 1 1 2 1 2 1
1 1 1 2 1 2 1 1
Any ideas?? Thank you!!
Upvotes: 0
Views: 134
Reputation: 389155
rle
will be helpful here :
apply(X, 1, function(x) unname(rle(x)$lengths))
#$`1`
#[1] 1 1 1 3 4
#$`2`
#[1] 1 1 1 1 2 1 2 1
#$`3`
#[1] 1 1 1 2 1 2 1 1
data
X <- structure(list(X1 = c(0L, 1L, 0L), X2 = c(2L, 0L, 2L), X3 = c(1L,
1L, 0L), X4 = c(0L, 2L, 1L), X5 = c(0L, 0L, 1L), X6 = c(0L, 0L,
0L), X7 = c(1L, 1L, 1L), X8 = c(1L, 2L, 1L), X9 = c(1L, 2L, 0L
), X10 = c(1L, 0L, 1L)), class = "data.frame", row.names = c("1", "2", "3"))
Upvotes: 1