Home > Enterprise >  Verifying if there are numeric values in data frame in R
Verifying if there are numeric values in data frame in R

Time:07-29

How can I check if there are any columns in the dataframe are of type numeric in R?

I want to be able to check for the data set iris. It should return true because there are 4 numeric values in this data set.

CodePudding user response:

With base R, we can use sapply with is.numeric - sapply loop over the columns, is.numeric returns TRUE if the columns is numeric and FALSE if not, then wrap with any to return a single TRUE/FALSE (i.e. if there are any TRUE values, it returns TRUE)

any(sapply(iris, is.numeric))
[1] TRUE

CodePudding user response:

dplyr option that counts number of numeric columns:

library(dplyr)
length(select_if(iris,is.numeric))
#> [1] 4

Created on 2022-07-28 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related