Reputation: 61
I have a matrix of the form:
[,1] [,2]
1 0
100 0
200 1
300 1
400 1
500 0
600 0
700 1
800 1
900 1
I am trying to make an R script that selects at least 3 continuous "1" values on column 2, for example, retrieving
200 1
300 1
400 1
700 1
800 1
900 1
but cannot find an easy way to do it. Has anyone encountered a problem like this one? I'd be really grateful!!! Thanks!!!
Upvotes: 0
Views: 162
Reputation: 12819
You can use rle
. Say your matrix is M
and your column of interest is 2
, then you can create a filter using this:
filter <- with(rle(M[,2]), rep(lengths>=3 & values==1, lengths))
Then filter the matrix using
M[filter,]
Upvotes: 3
Reputation: 89057
I would use rle
and inverse.rle
as follows:
r <- rle(mat[, 2])
r$values[r$values != 1 | r$lengths < 3] <- 0
keep <- as.logical(inverse.rle(r))
mat[keep, ]
Upvotes: 4