简体   繁体   中英

Extract rows from a matrix that meet a condition

I want to extract rows from a matrix, where there is overlap between the 3rd column of Mat1 and subset.vector.

Problem setup:

mat1= data.frame(matrix(nrow=10, ncol =5))
mat1[,2:5] = rnorm(40,0,1)
mat1[,1] = c(1,3,4)
mat1[,3] = c(500,120,7,9,10,11,14,53,12,13)
mat1

subset.vector <- c(500,120, 11, 13, 15)

output:

mat2 = mat1[c(1,2,6,10),]

I want to be able to do this for a matrix with 1000 rows without specifying the rows to extract individually. I have purposely setup subset.vector to include an element not in Mat1. I have also made sure that it is smaller in size.

You can use %in% to see where the subset.vector matches column 3 of mat1 like:

identical(mat2, mat1[mat1[,3] %in% subset.vector,])
#[1] TRUE

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