How to detect that a vector is subset of specific vector?

浪子不回头ぞ 提交于 2019-11-27 07:56:55

问题


I have two vectors (sets) like this:

first<-c(1,2,3,4,5)
second<-c(2,4,5)

how can I detect that whether second is subset of first or not? is there any function for this?


回答1:


Here's one way

> all(second %in% first)
[1] TRUE



回答2:


Here's another

setequal(intersect(first, second), second)
## [1] TRUE

Or

all(is.element(second, first))
## [1] TRUE



回答3:


If the order of the array elements matters, string conversion could help:

ord_match <- function(x,y){
    m <- c(0,grep(paste0(x,collapse=""),
                  paste0(y,collapse=""), fixed = T))
    return(as.logical(m)[length(m)])
}


来源:https://stackoverflow.com/questions/26831041/how-to-detect-that-a-vector-is-subset-of-specific-vector

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