jeudi 9 mars 2017

check equivalence of two vector, never mind order

suppose I have a number vectors, with one acting as a key:

key  <- c("A", "B")
vec1 <- c("B", "A")      #one that changes the order
vec2 <- c("A")           #one that is less one 
vec3 <- c("A", "B", "C") #one that is plus one
vec4 <- c("A", "B")      #this one is identical 

I want the check to go as follows:

if(vec [has all the elements of] key == TRUE)

so, results would go:

vec1 == TRUE
vec2 == FALSE
vec3 == FALSE
vec4 == TRUE

I've tried all() but...

all(key %in% vec1)  #TRUE  (as hoped)
all(key %in% vec2)  #FALSE (as hoped)
all(key %in% vec3)  #TRUE  (drat!)
all(key %in% vec3)  #TRUE  (as expected)

I could get the job done with multiple conditions:

all(key %in% vec1) & all(vec1 %in% key) #TRUE
all(key %in% vec2) & all(vec2 %in% key) #FALSE
all(key %in% vec3) & all(vec3 %in% key) #FALSE
all(key %in% vec4) & all(vec4 %in% key) #TRUE

I was wondering if there was a more elegant way?

Aucun commentaire:

Enregistrer un commentaire