【发布时间】:2020-08-08 08:23:48
【问题描述】:
mtcars %>%
group_by(cyl) %>%
group_map(~ head(.x, 2L))
谁能解释最后一行代码部分?
我知道管道,但~ head(.x, 2L) 是什么?
【问题讨论】:
-
对于每个组,打印头。它的语法很整洁。将其与
purrr::map(~head(.x))进行比较。
mtcars %>%
group_by(cyl) %>%
group_map(~ head(.x, 2L))
谁能解释最后一行代码部分?
我知道管道,但~ head(.x, 2L) 是什么?
【问题讨论】:
purrr::map(~head(.x)) 进行比较。
它是应用于每个组的匿名函数的简写。 .x 自动成为purrr 样式匿名函数的输入(另外.y 用于map2 函数)。
但您也可以使用传统的匿名函数:
mtcars %>%
group_by(cyl) %>%
group_map(., function(x) head(x, 2L)) # the `.` is just for illustration and can be omitted with the %>%
或者你可以写一个命名函数并在group_map()中使用:
new_fun <- function(x) {
head(x, 2L)
}
mtcars %>%
group_by(cyl) %>%
group_map(new_fun)
您显示的函数 (head(.x, 2L)) 对数据中的每个组应用一次。您可以查看您拥有的群组数量:
mtcars %>%
group_by(cyl) %>%
n_groups()
#> [1] 3
对于这些组中的每一个,都会打印前两行数据:
mtcars %>%
group_by(cyl) %>%
group_map(~ head(.x, 2L))
#> [[1]]
#> # A tibble: 2 x 10
#> mpg disp hp drat wt qsec vs am gear carb
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 22.8 108 93 3.85 2.32 18.6 1 1 4 1
#> 2 24.4 147. 62 3.69 3.19 20 1 0 4 2
#>
#> [[2]]
#> # A tibble: 2 x 10
#> mpg disp hp drat wt qsec vs am gear carb
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 21 160 110 3.9 2.62 16.5 0 1 4 4
#> 2 21 160 110 3.9 2.88 17.0 0 1 4 4
#>
#> [[3]]
#> # A tibble: 2 x 10
#> mpg disp hp drat wt qsec vs am gear carb
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 18.7 360 175 3.15 3.44 17.0 0 0 3 2
#> 2 14.3 360 245 3.21 3.57 15.8 0 0 3 4
【讨论】:
n_groups 来解释为什么只有3 个列表值。
n_groups(3) 会更容易显示 group_map 的工作原理,这就是结果长度为 3 的原因。
~ 用于在 purrr 包中的 map 函数中工作。与%>%无关。
~ 是上面function(.x) 的缩写,我使用了function(x),因为这是传统的写法。从那里开始,它实际上只是一个简单的匿名(即未命名)函数。