【发布时间】:2019-11-27 00:47:45
【问题描述】:
这个问题可能是关于 magrittr 但我不确定。如果我将数据(%>%)传递到下一个函数,据我所知,它会转到第一个参数。我有这个示例数据集 (df),并想提取 col1 到 col3 列中包含值 101 到 104 的所有行。
# A tibble: 5 x 4
ID col1 col2 col3
<dbl> <dbl> <dbl> <dbl>
1 101 102 201
2 201 202 203
3 104 NA 301
4 101 NA NA
5 201 301 302
我能做到
library(tidyverse)
df %>% filter(pmap_lgl(select(., starts_with("col")), ~any(c(...) %in% c(101:104))))
但是,当我只想获取布尔向量时,我会收到警告
df %>% pmap_lgl(select(., starts_with("col")), ~any(c(...) %in% c(101:104)))
Error: Can't convert a `spec_tbl_df/tbl_df/tbl/data.frame` object to function
我发现我可以使用
df %>% {pmap_lgl(select(., starts_with("col")), ~any(c(...) %in% c(101:104)))}
据我了解,df 通常会传递给 pmap 的第一个参数,但像这样它会转到点所在的位置。但是,为什么在第一种情况下不需要这样做。
数据:
df <- structure(list(ID = c(1, 2, 3, 4, 5), col1 = c(101, 201, 104,
101, 201), col2 = c(102, 202, NA, NA, 301), col3 = c(201, 203,
301, NA, 302)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -5L), spec = structure(list(cols = list(
ID = structure(list(), class = c("collector_double", "collector"
)), col1 = structure(list(), class = c("collector_double",
"collector")), col2 = structure(list(), class = c("collector_double",
"collector")), col3 = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1), class = "col_spec"))
【问题讨论】:
-
虽然这不能解决您的问题,但也许
filter_at()是您尝试做的替代方案?喜欢filter_at(df, vars( starts_with("col") ), any_vars(. %in% 101:104) ) -
@aosmith 谢谢,我明白了。我只是尝试熟悉 pmap 函数并玩了一下。