[英]How to compare each line of matrix with elements of vector in R
I would like to compare each line of given matrix with all elements of given vector: 我想将给定矩阵的每一行与给定向量的所有元素进行比较:
matrix <- matrix(c(c("var1","var2"),c("var4","var5"),c("var6","var7")),nrow = 3, ncol = 2)
vector <- c("var1", "var2", "var3", "var4", "var5", "var6")
The desired outcome would be just: TRUE because the elements of first line of matrix are contained within given vector. 期望的结果将是:TRUE,因为矩阵第一行的元素包含在给定向量中。
If the matrix was defined as: 如果矩阵定义为:
matrix <- matrix(c(c("var6","var7"),c("var1","var8"),c("var2","var9")),nrow = 3, ncol = 2)
The the desired outcome would be in this case FALSE because the elements of all rows of matrix are not contained within given vector. 在这种情况下,期望的结果将为FALSE,因为矩阵的所有行的元素都未包含在给定的向量内。 Any suggestions?
有什么建议么? Thanks!
谢谢!
Sounds like you just need apply
here 听起来您只需要在这里
apply
apply(matrix, 1, function(x) all(x %in% vector))
This looks across all the rows of the matrix to see if all values in a given row are in the vector. 这会遍历矩阵的所有行,以查看给定行中的所有值是否在向量中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.