删除小于 n 值的列? [英] drop columns that take less than n values?
本文介绍了删除小于 n 值的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个如下所示的数据框:
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))
我想创建一个新的数据框 df2 只包含取值超过 10 个的列.因此,在此示例中,它将是 v2、v3 和 v4.我怎样才能做到这一点?实际上,我的数据框有数千列.
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.
我试过了:
df2 <- df %>% select(which(length(unique(.))>10))
推荐答案
或者,您可以使用 dplyr
中的 select_if()
,您可以在其中将函数作为谓词传递给选择列:
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
# ...
或者在dplyr
版本>=1.00
df %>%
select(where(~ n_distinct(.) > 10))
这篇关于删除小于 n 值的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文