为什么apply()不适用于R中的数据帧?

时间:2021-03-10 18:33:38

I have a dataframe named "adult"

我有一个名为“成人”的数据框

> str(adult[, 1:2)
'data.frame':   32561 obs. of  15 variables:
 $ age      : int  39 50 38 53 28 37 49 52 31 42 ...
 $ worktp   : Factor w/ 9 levels " ?"," Federal-gov",..: 8 7 5 5 5 5 5 7 5 5 ...

> is.factor(adult[,1])
[1] FALSE

> is.factor(adult[,2])
[1] TRUE

Everything works well until I use

一切顺利,直到我使用

> apply(adult[,1:2], 2, function(x) is.factor(x))
age worktp 
FALSE  FALSE 

Why I got FALSE on worktp where is.factor() just gave me TRUE? I really need this apply() function to work on my dataframe. Should I use some other apply related functions?

为什么我在worktp上得到FALSE,其中is.factor()只是给了我真的?我真的需要这个apply()函数来处理我的数据帧。我应该使用其他一些应用相关的功能吗?

Thanks!

谢谢!

1 个解决方案

#1


6  

apply will convert your data into a matrix before processing it (see Details section in ?apply). The factor information is lost during this step.

apply会在处理之前将您的数据转换为矩阵(请参阅?apply中的详细信息部分)。在此步骤中丢失因子信息。

d <- data.frame(num=1:4, fac=factor(1:4))
d[, 2]
[1] 1 2 3 4
Levels: 1 2 3 4        # levels, hence a factor

m <- as.matrix(d)
m[, 2]
[1] "1" "2" "3" "4"     # no levels anymore

apply(d, 2, is.factor)

  num   fac 
FALSE FALSE             # no factors as converted to matrix

To get what you want you could use lapply

为了得到你想要的东西你可以使用lapply

lapply(d, is.factor)
$num
[1] FALSE

$fac
[1] TRUE

or sapply

或者是讽刺

sapply(d, is.factor)
  num   fac 
FALSE  TRUE 

#1


6  

apply will convert your data into a matrix before processing it (see Details section in ?apply). The factor information is lost during this step.

apply会在处理之前将您的数据转换为矩阵(请参阅?apply中的详细信息部分)。在此步骤中丢失因子信息。

d <- data.frame(num=1:4, fac=factor(1:4))
d[, 2]
[1] 1 2 3 4
Levels: 1 2 3 4        # levels, hence a factor

m <- as.matrix(d)
m[, 2]
[1] "1" "2" "3" "4"     # no levels anymore

apply(d, 2, is.factor)

  num   fac 
FALSE FALSE             # no factors as converted to matrix

To get what you want you could use lapply

为了得到你想要的东西你可以使用lapply

lapply(d, is.factor)
$num
[1] FALSE

$fac
[1] TRUE

or sapply

或者是讽刺

sapply(d, is.factor)
  num   fac 
FALSE  TRUE