【发布时间】:2021-01-29 14:16:31
【问题描述】:
假设我想在 same 具有不同过滤条件的数据集上应用 same 函数 (dplyr::filter)。
我可以在这里使用pmap 给出.l 中的参数列表以及我想在.f 中运行的函数。 filter 的参数是 .data(我已经指定),它在一个条件下工作,正如预期的那样:
purrr::pmap(.l = list(.data = list(mtcars)),
.f = dplyr::filter,
wt > 3)
#> [[1]]
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
#> Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
#> Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
#> Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
#> Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
#> Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
#> Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
#> Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4
#> Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3
#> Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3
#> Merc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3
#> Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4
#> Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4
#> Chrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4
#> Dodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2
#> AMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2
#> Camaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4
#> Pontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2
#> Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4
#> Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8
但我不知道如何通过多个过滤条件:
purrr::pmap(.l = list(.data = list(mtcars)),
.f = dplyr::filter,
list(alist(wt > 3), alist(wt > 5)))
#> Error: Problem with `filter()` input `..1`.
#> x Input `..1` must be of size 32 or 1, not size 2.
#> ℹ Input `..1` is `alist(wt > 3, wt > 5)`.
我该怎么做?
我期待两个数据帧的list:一个使用条件wt > 3 过滤,另一个使用wt > 5。
【问题讨论】:
-
pmap适用于您想要(引用文档)“同时迭代多个参数”的情况。它将数据框解释为参数列表,并将filter单独应用于每一列。您持有.data参数常量,并且仅在 1 个参数(过滤条件)上 迭代,所以我认为您想要map而不是pmap。 -
但是我仍然不确定如何将其与论点的 NSE 配对...我相信有人会过来演示。
-
@GregorThomas 谢谢,我已经编辑了我的问题以解决您的问题。
-
如果您期望 2 个数据帧,那么使用
pmap和list(mtcars)不是正确的方法。正如@GregorThomas 所建议的,map是您想要使用的:purrr::map(.x = c(3, 5), .f = function(x){ mtcars %>% dplyr::filter(wt > x) }) -
@SavedByJESUS 谢谢!您能否发布您的解决方案,以便我接受并关闭它?