Remove columns that have only a unique value

You can use select(where()).

Suppose I have a data frame like this:

df <- data.frame(A = LETTERS[1:5], B = 1:5, C = 2)

df
#>   A B C
#> 1 A 1 2
#> 2 B 2 2
#> 3 C 3 2
#> 4 D 4 2
#> 5 E 5 2

Then I can do:

df %>% select(where(~ n_distinct(.) > 1))

#>   A B
#> 1 A 1
#> 2 B 2
#> 3 C 3
#> 4 D 4
#> 5 E 5

Some base R options:

  • Using lengths + unique + sapply
subset(df,select = lengths(sapply(df,unique))>1)
  • Using Filter + length + unique
Filter(function(x) length(unique(x))>1,df)

Tags:

R