Search code examples
stringrlistdataframecoercion

logical query on mixed (character and numeral) variable


I didn't think this would be so difficult but I've struggled for some time... I hope it's something simple I am missing :) I need to be able to logically query a dataframe containing variables that are a mixture of character strings and numerals.

LAMBDA<-data.frame(cbind(list(1,"lequiv"),list("lequiv",0)))
LAMBDA!=1

What is the best way to achieve this, so that the character strings, which clearly do not equal 1, are reported as FALSE, rather than NA? Thanks.


Solution

  • Instead of testing for elements which are equal to the number 1, you could try testing for elements which are equal to the string "1". For example:

    > LAMBDA!="1"
            X1   X2
    [1,] FALSE TRUE
    [2,]  TRUE TRUE
    

    whereas:

    > LAMBDA!=1
            X1   X2
    [1,] FALSE   NA
    [2,]    NA TRUE
    

    In the first case, R is clever enough to coerce the value 1 in your data frame to be a string before testing for equivalence. In the second case it cannot coerce "lequiv" to a number betore testing for equivalence and therefore returns NA (and a warning message).