select columns with contains only numeric values >= 0

Viewed 67

I want to select columns with numeric values >= 0.

cities <- c("Nantes", "Paris", "London", "Munchen")
variable1 <- c(-100, 20, 5, 30)
variable2 <- c(10, 13, 2, 30)
variable3 <- c(10, 200, -5, 300)
df <- data.frame(cities, variable1, variable2, variable3)

What I tried without success :

library(tidyverse)
df %>% select_if(is.numeric >=0)

What I want :

cities variable2
1  Nantes        10
2   Paris        13
3  London         2
4 Munchen        30
4 Answers

You can do:

df %>%
 select_if(~ is.numeric(.) && all(. >= 0))

  variable2
1        10
2        13
3         2
4        30

If the goal is to keep columns with strings or with all values >= 0, then:

df %>%
 select_if(~ is.character(.) || all(. >= 0))

   cities variable2
1  Nantes        10
2   Paris        13
3  London         2
4 Munchen        30

in base R

df[c(T,apply(df[-1],2,function(x) all(x>=0)))]

   cities variable2
1  Nantes        10
2   Paris        13
3  London         2
4 Munchen        30

We can use Filter in base R

Filter(function(x) is.numeric(x) && all(x > 0), df)
#  variable2
#1        10
#2        13
#3         2
#4        30

You can paste0 all columns into strings and substract (-) those columns which match the pattern -:

df[, -which(grepl("-", apply(df, 2, paste0, collapse = " ")))]
   cities variable2
1  Nantes        10
2   Paris        13
3  London         2
4 Munchen        30
Related