r - 如何在 dplyr 中过滤列表参数和多个字符串的组合

标签 r functional-programming

给定一个数据框:

v1_attr1 <- c(1,0,0,0,1,0,0,0,1,1) %>% as.integer ()
v1_attr2 <- c(0,1,0,0,1,1,1,1,1,1) %>% as.integer ()
v2_attr1 <- c(0,0,1,0,0,1,1,1,0,0)  %>% as.integer ()
v2_attr2 <- c(0,0,0,1,0,1,1,1,0,0)  %>% as.integer ()

df <- data.frame (v1_attr1, v1_attr2, v2_attr1, v2_attr2)

如何为每个 v[[x]]attr 设置过滤器?

我尝试了以下代码来获取由 attr 过滤的每个 data.frame 中的行数。

library(dplyr)

# create list for vs
list_vs <- list ("v1", "v2")

# set multiple attr filter for each v[[x]] to get the respective number of rows in each filtered data.frame (presented in a list)
filtered <- lapply (list_vs, function (x){
  df %>% filter (noquote(paste0(list_vs[[x]], "_attr1")) == 1 | noquote(paste0(list_vs[[x]], "_attr2")) == 1) %>%
  nrow ()
})

尽管这段代码没有返回错误,filtered[[x]] 的结果始终为 0。我需要如何正确设置过滤器参数以获得所需的行数在每个 data.frame 中?我使用了 noquote 因为否则过滤参数将被粘贴在引号中。

最佳答案

dplyrpurrr 选项可以是:

map(.x = list_vs,
    ~ df %>%
     filter_at(vars(starts_with(.x)), any_vars(. == 1)))

[[1]]
  v1_attr1 v1_attr2 v2_attr1 v2_attr2
1        1        0        0        0
2        0        1        0        0
3        1        1        0        0
4        0        1        1        1
5        0        1        1        1
6        0        1        1        1
7        1        1        0        0
8        1        1        0        0

[[2]]
  v1_attr1 v1_attr2 v2_attr1 v2_attr2
1        0        0        1        0
2        0        0        0        1
3        0        1        1        1
4        0        1        1        1
5        0        1        1        1

关于r - 如何在 dplyr 中过滤列表参数和多个字符串的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61542684/

相关文章:

functional-programming - 使用 Hindley Milner 类型推断的 SML 中类型定义的增长

C++:如何做Scheme的 "map"

r - 如何在R中带有索引的对象中添加数据?

r - 时间序列数据的主成分分析(PCA): spatial and temporal pattern

javascript - 如何访问在 Shiny 中渲染的 rhandsontable 的 JS 变量名称?

r - 如何通过R中的多列计算逻辑值?

R: If 语句函数 with apply

r - 如何使用autoconf重新生成配置文件?

javascript - Javascript "delay evaluation"想要避免急切评估时如何运行?

javascript - 在 JavaScript 中构建数组数组的函数式方法