删除小于 n 值的列?

编程入门 行业动态 更新时间:2024-10-24 10:18:56
本文介绍了删除小于 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 值的列?

本文发布于:2023-11-30 21:07:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651473.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!