loveR
loveR

Reputation: 509

Select only numerics or integers

I wanted to select only those columns which are integer and numeric data types with dplyr.

There is a post about selecting columns that are numeric data type

dat <- dplyr::select_if(dat, is.numeric)

I was wondering if I could use something similar that can select columns that are numeric and integer both:

dat <- dplyr::select_if(dat, is.numeric && is.integer)

or

dat <- dplyr::select_if(dat, c(is.numeric, is.integer))

Although both above seem not be working.

Upvotes: 1

Views: 1176

Answers (1)

user4117783
user4117783

Reputation:

A variable that is both integer and numeric is integer (every integer is also a numeric). So either you use is.numeric to catch all integers and reals or you use as.integer to catch only the integer ones.

If you're not too attached to using dplyr, this will do (using is.numeric here).

dat_selected <- dat[sapply(dat, is.numeric)]

Upvotes: 3

Related Questions