Unexpected behavior of is.logical and is.factor in application

Recently, I was surprised that is.logical and is.factor could not fail using apply - at least they did not deliver the correct result.

Here is my small reproducible example:

 # generate a dataset that contains a couple of modes someDf <- data.frame(fac1=gl(2,3,12), int=1:12, char=letters[1:12], logi=rep(c(T,F),6), fac2=gl(3,2,12)) # hooray, this did work, got factors, int, # characters and logical str(someDf) # I expected this to work, but it didn't # everything is just FALSE apply(someDf,2,is.logical) 

I did not give up and found a way to sneak around this.

 unlist(lapply(names(someDf),function(x) is.logical(someDf[,x]))) 

Although this gives the correct result, I wonder why it should be so complicated and is it easier to solve. Any ideas?

Hint: I saw that

 apply(someDf,2,class) 

provides all characters . This is also unexpected. Maybe something with eval doing a trick that I could not find.

+4
source share
1 answer

Since data.frame is a list , you should use lapply or sapply :

 sapply(someDf, is.logical) fac1 int char logi fac2 FALSE FALSE FALSE TRUE FALSE 

The reason your code doesn't work is because apply needs a matrix as its argument and forces the matrix if you provide a data frame. Since a matrix can only contain elements of one class, your values ​​are converted to character . Try:

 as.matrix(someDf) fac1 int char logi fac2 [1,] "1" " 1" "a" " TRUE" "1" [2,] "1" " 2" "b" "FALSE" "1" [3,] "1" " 3" "c" " TRUE" "2" [4,] "2" " 4" "d" "FALSE" "2" [5,] "2" " 5" "e" " TRUE" "3" [6,] "2" " 6" "f" "FALSE" "3" [7,] "1" " 7" "g" " TRUE" "1" [8,] "1" " 8" "h" "FALSE" "1" [9,] "1" " 9" "i" " TRUE" "2" [10,] "2" "10" "j" "FALSE" "2" [11,] "2" "11" "k" " TRUE" "3" [12,] "2" "12" "l" "FALSE" "3" 
+7
source

Source: https://habr.com/ru/post/1435218/


All Articles