最近,我对 is.logicalis.factor 不能用 apply 开箱即用的事实感到惊讶——至少它们没有提供正确的结果。

这是我的可重现的小例子:

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

我没有放弃,并找到了一种方法来绕过这个。
unlist(lapply(names(someDf),function(x) is.logical(someDf[,x])))

虽然这提供了正确的结果,但我想知道为什么它必须如此复杂,以及是否有更简单的解决方案。有任何想法吗?

提示:我已经看到了
apply(someDf,2,class)

提供所有 characters 。这也是意料之中。也许 eval 的某些东西可以解决我找不到的问题。

最佳答案

由于 data.frame 是 list ,您应该使用 lapplysapply :

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

您的代码不起作用的原因是 apply 需要一个矩阵作为其参数,如果您提供数据框,则强制转换为矩阵。由于矩阵只能包含单个类的元素,因此您的值将转换为 character 。尝试一下:
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"

关于r - is.logical 和 is.factor in apply 的意外行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12508416/

10-12 20:19