我想知道为什么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
答案 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
。