Gennaro Tedesco Gennaro Tedesco - 1 year ago 122
R Question

Check if list contains another list in R

I want to check if a list (or a vector, equivalently) is contained into another one, not if it is a subset of its. Let us assume we have

r <- c(1,1)
s <- c(5,2)
t <- c(1,2,5)

The function should behave as follows:

# as (1,1) is not contained in (1,2,5) since the former
# contains two 1 whereas the latter only one.

[1] TRUE

The operator
checks for subsets, hence it would return
in both cases, likewise
. I am sure there is a one-liner but I just do not see it.

Answer Source

Another custom-function version, checking whether the number of elements (length()) of the non-equal elements (setdiff) is equal to the difference in the vectors' length:

r <- c(1,1)
s <- c(5,2)
t <- c(1,2,5)
w <- c(1, 1, 3, 6)

# Does vector x contain vector y?
is.contained <- function(x, y) {
  length(setdiff(x, y)) == length(x) - length(y)

is.contained(r, t)
#> [1] FALSE
is.contained(t, s)
#> [1] TRUE
is.contained(w, r)
#> [1] TRUE
is.contained(w, s)
#> [1] FALSE
is.contained(r, w)
#> [1] FALSE
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download