R sapply is.factor

夙愿已清 提交于 2019-12-07 00:28:06

问题


I'm trying to separate a dataset into parts that have factor variables and non-factor variables.

I'm looking to do something like:

This part works:

factorCols <- sapply(df1, is.factor)
factorDf <- df1[,factorCols]

This part won't work:

nonFactorCols <- sapply(df1, !is.factor)

due to this error:

Error in !is.factor : invalid argument type

Is there a correct way to do this?


回答1:


Correct way:

nonFactorCols <- sapply(df1, function(col) !is.factor(col))
# or, more efficiently
nonFactorCols <- !sapply(df1, is.factor)
# or, even more efficiently
nonFactorCols <- !factorCols



回答2:


Joshua gave you the correct way to do it. As for why sapply(df1, !is.factor) did not work:

sapply is expecting a function. !is.factor is not a function. The bang operator returns a logical value (albeit, it cannot take is.factor as an argument).

Alternatively, you could use Negate(is.factor) which does in fact return a function.



来源:https://stackoverflow.com/questions/19169051/r-sapply-is-factor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!