Suppose i have a data frame like the following:
df <- data.frame(v1 = sample(1:10, 100, replace = T), v2 = sample(LETTERS, 100, replace = T),
Clunky but it works...
x<-as.data.frame(t(apply(df,2,function(x) length(x[unique(x)]))>10))
df[,names(x[,x>0])]
Alternatively, you can use select_if()
from dplyr
where you can pass a function as predicate to select columns:
library(dplyr)
df %>% select_if(function(col) n_distinct(col) > 10)
# v2 V3 v4
#1 T a 12
#2 R k 7
#3 L l 1
# ...