Gennaro Tedesco - 9 months ago 74

R Question

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:

`is.contained(r,t)`

[1] FALSE

# as (1,1) is not contained in (1,2,5) since the former

# contains two 1 whereas the latter only one.

is.contained(s,t)

[1] TRUE

The operator

`%in%`

`TRUE`

`all`

`any`

Answer

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
```

Source (Stackoverflow)