Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test if three variables are equal [R]

Tags:

equality

r

I'm trying to do if else statement which includes a condition if three variables in the data frame equal each other.

I was hoping to use the identical function but not sure whether this works for three variables.

I've also used the following but R doesn't seem to like this:

geno$VarMatch  <- ifelse((geno[c(1)] != '' & geno[c(2)] != '' & geno[c(3)] != '') 
& (geno[c(5)] == geno[c(4)] == geno[c(6)]), 'Not Important', 'Important')

Keeps telling me:

Error: unexpected '==' 

Am I supposed to specify something as data.frame/vector etc... Coming from an SPSS stand point, I'm slightly confused.

Sorry for the simplistic query.

like image 978
user2726449 Avatar asked Nov 13 '13 23:11

user2726449


People also ask

How do you know if three variables are equal?

To have a comparison of three (or more) variables done correctly, one should use the following expression: if (a == b && b == c) .... In this case, a == b will return true, b == c will return true and the result of the logical operation AND will also be true.

How do you test for equality in R?

Check if Two Objects are Equal in R Programming – setequal() Function. setequal() function in R Language is used to check if two objects are equal. This function takes two objects like Vectors, dataframes, etc. as arguments and results in TRUE or FALSE, if the Objects are equal or not.


2 Answers

I see so complicated results, mine is simple:

all(sapply(list(a,b,c,d), function(x) x == d))

returns TRUE, if all equals d all equals each other.

like image 165
Peter.k Avatar answered Sep 23 '22 13:09

Peter.k


Here's a recursive function which generalises to any number of inputs and runs identical on them. It returns FALSE if any member of the set of inputs is not identical to the others.

ident <- function(...){
    args <- c(...) 
    if( length( args ) > 2L ){
       #  recursively call ident()
       out <- c( identical( args[1] , args[2] ) , ident(args[-1]))
    }else{
        out <- identical( args[1] , args[2] )
    }    
    return( all( out ) )
}

ident(1,1,1,1,1)
#[1] TRUE
ident(1,1,1,1,2)
#[1] FALSE
like image 35
Simon O'Hanlon Avatar answered Sep 21 '22 13:09

Simon O'Hanlon