为什么`as.factor`在R中通过`apply`函数应用时不起作用?

时间:2014-10-08 10:37:37

标签: r apply r-factor

我想知道为什么as.factor功能在apply中通过R功能应用后无效?

> df.nrow <- 10
> df <- data.frame(col1=sample(c("a","b","c"), df.nrow, TRUE),
+                  col2=sample(c("d","e","f"), df.nrow, TRUE),
+                  col3=sample(c("g","h","i"), df.nrow, TRUE))
> apply(df, 2, is.factor)
 col1  col2  col3 
FALSE FALSE FALSE 
> df <- apply(df, 2, as.factor)
> apply(df, 2, is.factor)
 col1  col2  col3 
FALSE FALSE FALSE 

1 个答案:

答案 0 :(得分:5)

我认为这是因为apply简化了返回矩阵的结果。来自?apply

If ‘X’ is not an array but an object of a class with a non-null
    ‘dim’ value (such as a data frame), ‘apply’ attempts to coerce it
    to an array via ‘as.matrix’ if it is two-dimensional (e.g., a data
    frame) or via ‘as.array’.

事实上,您的原始数据框是您想要的。请尝试str(df)sapply(df, is.factor)进行验证。除非stringsAsFactors=FALSE

,否则基本上字符向量总是强制为因子