rdataframedplyrisnumeric

Extract all columns except numeric in R data frame


In my project, I want to extract all the columns except numeric from my R data frame, as this question I used the same method and just put a not gate into is.numeric() R function but it is not working

This gives all the numaric data,

x<-iris %>% dplyr::select(where(is.numeric))

But this does not work as expected,

x<-iris %>% dplyr::select(where(!is.numeric))

Note: Finally the output data frame should only contain the species column in the iris dataset


Solution

  • purrr package from tidyverse serves exactly what you want by purrr::keep and purrr::discard

    library(purrr)
    
    x <- iris %>% keep(is.numeric)
    

    by these piece of code, you set a logical test in keep function and only the columns which passed the test stays.

    to reverse that operation and achieve to your wish, you can use discard from purrr also;

    x <- iris %>% discard(is.numeric)
    

    you can think discard as keep but with !is.numeric

    or alternatively by dplyr

    x <- iris %>% select_if(~!is.numeric(.))