R sapply is.factor

I am trying to split a data set into parts that have factor variables and non-factor variables.

I want to do something like:

This part works:

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

This part will not work:

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

due to this error:

 Error in !is.factor : invalid argument type 

Is there a proper way to do this?

+6
source share
2 answers

The right way:

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

Joshua gave you the right way to do this. As for why sapply(df1, !is.factor) didn't work:

sapply expects a function. !is.factor not a function. The bang operator returns a boolean (although it cannot accept is.factor as an argument).

Alternatively, you can use Negate(is.factor) , which actually returns a function.

+8
source

Source: https://habr.com/ru/post/955214/


All Articles