0

I am new to R. I am good with python. In python we have a function select_dtypes(df,include='datatype', exclude='datatype')

So if I want to find out all numeric columns, I can do select_dtype(df,include='numeric') and I get list of numeric columns only. This will select all columns which are numeric(float, int32, int64 etc.) . I can also explicitly select only int columns and so on. Similarly I can also exclude columns of a particular datatype

How do I achieve the same in R.

df

Int1  Int2   Char1   Char2  factor1  flaot1   #lets say these are the columns of a df
noob
  • 3,601
  • 6
  • 27
  • 73
  • 1
    Does this answer your question? [Selecting only numeric columns from a data frame](https://stackoverflow.com/questions/5863097/selecting-only-numeric-columns-from-a-data-frame) – fabla Apr 11 '20 at 14:29

1 Answers1

2

We can use select_if from dplyr after reading the data into R

library(dplyr)
df1 %>%
     select_if(is.numeric)

Or if we need to negate

library(purrr)
df1 %>%
     select_if(negate(is.numeric))

Or

df1 %>%
    select_if(~ !is.numeric(.))

Or in base R, we can check with sapply

i1 <- sapply(df1, is.numeric)
df1[i1]

If we need to exclude, negate (!)

df1[!i1]

Or with Filter

Filter(is.numeric, df1)

Or Negate

Filter(Negate(is.numeric), df1)

With a reproducible example

Filter(Negate(is.factor), iris)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • pls include exclude too...how to exclude columns of a particular datatype – noob Apr 11 '20 at 14:25
  • hi error: could not find function "negate"...can you tell me which is the library? i have used funprog...your first negate was with small n it seems..error solved – noob Apr 11 '20 at 15:43
  • @ShailajaGuptaKapoor sorry, forgot. it is from `purrr` updated – akrun Apr 11 '20 at 15:45