R function to check if a vector is a subset of another

Viewed 92

I need to check if values_saved_dice is a subset from x, for example

values_saved_dice <- c(2,2,2)
x <- c(6,3,2,2,5)

I tried the following function, expecting it should return FALSE.

all(is.element(value_saved_dices, x)

But it returns TRUE, when apparently it should be FALSE - because the number "2" appeared 3 times in value_saved_dices and x only has "2" twice.

Would appreciate any help, thanks!

2 Answers

We may paste the vector into string and use grepl to check if the substring is found or not

grepl(paste(values_saved_dice, collapse = ""), paste(x, collapse = ""))
[1] FALSE

You could create a function:

cont = function(x, y) {
  z = x[x %in% setdiff(x, y)]
  length(z) == length(x) - length(y)
}

Output:

> values_saved_dice <- c(2,2,2) # triple 2
> x <- c(6,3,2,2,5)
> cont(x, values_saved_dice)
[1] FALSE
> values_saved_dice <- c(2,2)  # double 2
> x <- c(6,3,2,2,5)
> cont(x, values_saved_dice)
[1] TRUE
Related