[英]What is tilde in this context of R?
mtcars %>%
group_by(cyl) %>%
group_map(~ head(.x, 2L))
Can anyone explain last line of code part?谁能解释最后一行代码部分? I know about the pipe but what is
~ head(.x, 2L)
?我知道 pipe 但什么是
~ head(.x, 2L)
?
It's a shorthand for an anonymous function that is applied to every group.它是应用于每个组的匿名 function 的简写。
.x
is automatically the input in purrr
style anonymous functions (and additionally .y
for map2
functions). .x
自动成为purrr
风格匿名函数的输入(另外.y
用于map2
函数)。
But you can use a traditional anonymous functions as well:但是您也可以使用传统的匿名函数:
mtcars %>%
group_by(cyl) %>%
group_map(., function(x) head(x, 2L)) # the `.` is just for illustration and can be omitted with the %>%
Or you can write a named function and use it in group_map()
:或者你可以写一个命名为 function 并在
group_map()
中使用它:
new_fun <- function(x) {
head(x, 2L)
}
mtcars %>%
group_by(cyl) %>%
group_map(new_fun)
The function you show ( head(.x, 2L)
) is applied once to every group in the data.您显示的 function (
head(.x, 2L)
) 对数据中的每个组应用一次。 You can check how many groups you have with:您可以检查您有多少组:
mtcars %>%
group_by(cyl) %>%
n_groups()
#> [1] 3
For each of these groups, the first two rows of the data is printed:对于这些组中的每一个,打印数据的前两行:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.