Sakti
Sakti

Reputation: 61

Selecting R matrix values by blocks

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

Answers (2)

Ferdinand.kraft
Ferdinand.kraft

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

flodel
flodel

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

Related Questions