简体   繁体   English

如何将矩阵的每一行与R中的向量元素进行比较

[英]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.

相关问题 如何将矩阵的每一行除以 R 中向量的元素 - How to divide each row of a matrix by elements of a vector in R 用列表填充矩阵,其中列表中的每个向量可以是1-7个元素[R] - populating a matrix with a list, where each vector in the list may be 1 - 7 elements [R] 如何有效地将矩阵的每一行与R中列表的每个部分进行比较? - How to efficiently compare each row of a matrix to each section of a list in R? R中矩阵中矢量元素的差异 - Difference of a vector elements in a matrix in R 在R中:如何测试列表或向量中矩阵元素的隶属关系 - In R: How do I test for membership of matrix elements in a list or a vector 如何用 R 中命名向量的值替换 char 矩阵中的元素 - How to replace elements in char matrix with values from named vector in R 如何使用向量元素作为r中矩阵位置的坐标? - How to use vector elements as coordinates for matrix positions in r? 如何选择向量中的相邻元素并将它们放入R中的列表或矩阵中 - how to select neighbouring elements in a vector and put them into a list or matrix in R 用R中am * n数值矩阵的每一列的正元素之和创建向量 - Create a vector with the sum of the positive elements of each column of a m*n numeric matrix in R R:如何计算向量中每个元素的最大重复项 - R: how to account maximum duplicates in each elements of a vector
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM