r - 使用 R 中的数据集位置进行过滤
问题描述
我不太熟悉 R 中的 dplyr 函数。但是,我想将我的数据集过滤到某些条件下。
假设我的数据集中有 100 多个属性。我想执行具有多个条件的过滤器。
我可以将我的编码过滤器放在列的位置而不是它们的名称,如下所示:
y = filter(retag, c(4:50) != 8 & c(90:110) == 8)
我已经尝试过几次类似的编码,但仍然没有得到结果。
我也尝试过如下编码,但不确定如何在 rowSums 函数中添加其他条件。
retag[rowSums((retag!=8)[,c(4:50)])>=1,]
我发现的唯一示例是使用数据集名称而不是位置。
或者有什么方法可以使用数据集位置进行过滤,因为我的数据非常庞大。
解决方案
您可以使用filter()
和的组合across()
。我没有您的数据框版本,retag
所以我创建了自己的数据框作为示例
set.seed(2000)
retag <- tibble(
col1 = runif(n = 1000, min = 0, max = 10) %>% round(0),
col2 = runif(n = 1000, min = 0, max = 10) %>% round(0),
col3 = runif(n = 1000, min = 0, max = 10) %>% round(0),
col4 = runif(n = 1000, min = 0, max = 10) %>% round(0),
col5 = runif(n = 1000, min = 0, max = 10) %>% round(0)
)
# filter where the first, second, and third column all equal 5 and the fourth column does not equal 5
retag %>%
filter(
across(1:3, function(x) x == 5),
across(4, function(x) x != 5)
)
推荐阅读
- javascript - Electron:将用户可编辑的数据存储在 .txt 文件中
- python - 使用 Python 和 Tkinter,我将如何在 .mainloop() 的每个循环中运行代码?
- cassandra - 运行 Debezium cassandra 连接器时出现 Cassandra 错误
- sql - 如何使用 Bigquery SQL 中的另一个表对列进行分桶?
- python - Pandas:根据 IF 条件创建复制值列到其下方的单元格
- spring - WebClient 请求的简单日志转储?
- python - Tweepy 只回复新的提及并忽略我已经回复的那些
- migration - 通过 OpenUpgrade 将 odoo11 升级到 odoo13 的问题
- powershell - 无法获取 Service Fabric PowerShell 模块
- string - 最长有效括号问题