删除少于n个值的列? [英] drop columns that take less than n values?

查看:69
本文介绍了删除少于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() $ c>,您可以在其中传递谓词以选择列:

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

这篇关于删除少于n个值的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆