JC3019
JC3019

Reputation: 383

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.

Upvotes: 1

Views: 130

Answers (1)

GKi
GKi

Reputation: 39657

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

Upvotes: 1

Related Questions