Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select non-numeric columns using dplyr::select_if

Tags:

I need to select all columns that are not numeric. I can select all numeric columns easily using select_if:

mtcars %>% select_if(is.numeric) 

What if I want to select non-numeric columns? I tried:

mtcars %>% select_if(!is.numeric) 

But I got error message below:

Error in !is.numeric : invalid argument type 

Thanks a lot for help!

like image 501
zesla Avatar asked Jan 24 '18 20:01

zesla


People also ask

How do I select only numeric columns in R?

We can use select_if() function to get numeric columns by calling the function with the dataframe name and isnumeric() function that will check for numeric columns.

How do I extract a numerical variable in R?

In R, you can extract numeric and factor variables using sapply function.

How do I select only numeric columns from a data frame?

To select columns that are only of numeric datatype from a Pandas DataFrame, call DataFrame. select_dtypes() method and pass np. number or 'number' as argument for include parameter.


2 Answers

You can use purrr's negate() which is included if you use library(tidyverse) rather than just library(dplyr)

library(tidyverse) iris %>% select_if(negate(is.numeric)) 
like image 66
MrFlick Avatar answered Oct 20 '22 05:10

MrFlick


You can use a purrr-style anonymous function, provided you have a reasonably recent version of dplyr:

library(dplyr)  iris %>% select_if(~!is.numeric(.x)) %>% head() #>   Species #> 1  setosa #> 2  setosa #> 3  setosa #> 4  setosa #> 5  setosa #> 6  setosa 

or the old-style funs notation still works, e.g.

iris %>% select_if(funs(!is.numeric(.))) %>% head() #>   Species #> 1  setosa #> 2  setosa #> 3  setosa #> 4  setosa #> 5  setosa #> 6  setosa 
like image 36
alistaire Avatar answered Oct 20 '22 06:10

alistaire