user1828605
user1828605

Reputation: 1735

Given a vector of column names, how to check if all of them are numeric?

If I have a vector of column names from a data frame, how can I check if they’re all numeric. If there’s any non-numeric variable, how to identify it?

I’ve tried the first one but couldn’t move to the second one until I could solve it.

When I tried the following, I keep getting false

all(df[,numeric_cols] %>% is.numeric())

Is there a one line code that I can put within if condition, and find the one that is not numeric?

Upvotes: 0

Views: 270

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388862

You can check if all class are numeric by

all(sapply(df[,numeric_cols], class) == "numeric")

To identify non-numeric columns one way would be :

names(Filter(function(x) !is.numeric(x), df[,numeric_cols]))

Upvotes: 1

Related Questions