Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

r - drop columns that take less than n values?

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),
                 V3 = sample(letters, 100, replace = T), v4 = sample(1:15, 100, replace = T))

I would like to create a new data frame df2 only includes the columns that take more than 10 values. So, in this example it would be v2, v3, and v4. How can I do that? In practice my data frame has thousands of columns.

I tried this:

df2 <- df %>% select(which(length(unique(.))>10))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
# ...

Or using select with where in dplyr version >=1.00

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...