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?
Correct way:
nonFactorCols <- sapply(df1, function(col) !is.factor(col))
# or, more efficiently
nonFactorCols <- !sapply(df1, is.factor)
# or, even more efficiently
nonFactorCols <- !factorCols
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.