简体   繁体   中英

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!!!

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, ]

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,]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM