Check if vector in a matrix

末鹿安然 提交于 2020-07-22 06:39:05

问题


I have a matrix

new<-matrix(9,4,4)
new[1,1]<-0

v1<-c(0,0)

new thus looks like this:

0 9 9 9 
9 9 9 9
9 9 9 9
9 9 9 9

I now want to check if this matrix contains the vector v1. So I did

v1 %in% new 

and obtain TRUE TRUE although I would like to check the whole vector of two zeros in a row/ column and thus would like to get a FALSE.


回答1:


You can use rollapply from zoo to test if matrix contains a vector:

library(zoo)
any(apply(new, 2, rollapply, length(v1), identical, v1))
#[1] FALSE

new[2,1] <- 0
any(apply(new, 2, rollapply, length(v1), identical, v1))
#[1] TRUE



回答2:


You can use a combination of isTRUE and all.equal, while intersect the vector with the matrix i.e.

isTRUE(all.equal(v1, intersect(v1, new)))
#[1] FALSE

v2 <- c(0, 9)
all.equal(v2, intersect(v2, new))
#[1] TRUE



回答3:


Is this what you want?

The vector has two values, so if you want to check whether it is contained in the matrix you will have to paste the two values together to obtain 0,0:

paste0(v1, collapse = ",") %in% new
[1] FALSE

or this, which compares the string 0,0 from the pasted-together vector to the pasted-together rows of the matrix:

paste0(v1, collapse = ",") %in% apply(new, 2, paste0, collapse = ",")
[1] FALSE

or this, which searches for 0,0 in the corresponding pairs of two digts separated by comma in the pasted-together rows of the matrix:

library(stringr)
paste0(v1, collapse = ",") %in% unlist(str_split(apply(new, 2, paste0, collapse = ","), "(?<=\\d,\\d),(?=\\d,\\d)"))

This latter solution seems the most likely as it searches for 0,0 %in% this vector, which is the output of unlist(str_split(apply(new, 2, paste0, collapse = ","), "(?<=\\d,\\d),(?=\\d,\\d)")):

[1] "0,9" "9,9" "9,9" "9,9" "9,9" "9,9" "9,9" "9,9"


来源:https://stackoverflow.com/questions/62693039/check-if-vector-in-a-matrix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!