Recently I was surprised by the fact that is.logical and is.factor weren’t able to run out of the box with apply – at least they did not the deliver the correct result.
Here’s my little 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 didn’t give up and found a way to sneak around this.
unlist(lapply(names(someDf),function(x) is.logical(someDf[,x])))
Though this delivers the correct result I wonder why it has to be that complicated and whether there’s a simpler to solution to it. Any ideas?
Hint: I have seen that
apply(someDf,2,class)
delivers all characters. This is unexpected, too. Maybe something with eval does the trick I couldn’t find.
Since a data.frame is a
list, you should uselapplyorsapply:The reason that your code doesn’t work is because
applyneeds a matrix as its argument, and coerces to a matrix if you provide a data frame. Since a matrix can only have elements of a single class, your values get converted tocharacter. Try it: