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.

有帮助吗?

解决方案

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).

其他提示

I think you're looking for factors here.

If you look at str(LAMBDA) you'll see that X1 is a list with two elements, one stored as numeric, one as character.

If you instead create your list as follows:

l1 <- data.frame(X1=c(1,"lequiv"),
                 X2=c("lequiv",2)
                  )

it will look just the same when printed, but the variables are represented as factors.

Then l1==1 gives:

        X1    X2
[1,]  TRUE FALSE
[2,] FALSE FALSE
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top