不能在 r 中使用带有 magrittr 的占位符
Can't use placeholder with magrittr in r
我很好奇为什么下面的代码不能运行。我认为点 .
是一个占位符并将 mtcats
传递给该位置。
table(mtcars$cyl)
mtcars %>% table(.$cyl)
管道%>%
将左边的对象作为第一个参数粘贴到
右边的功能。所以你基本上执行:
table(mtcars, mtcars$cyl)
#> Error in table(mtcars, mtcars$cyl): all arguments must have the same length
正如 agr0naut91 评论的那样,这可以通过使用大括号来解决:
library(magrittr)
mtcars %>% {table(.$cyl)}
#>
#> 4 6 8
#> 11 7 14
只要你想通过管道传输到一个不是管道的函数,它就可以工作
友好的,这通常意味着它没有 data.frame
参数
作为第一个参数。
使用 dplyr::count()
您可以获得与 base::table()
相当的输出,
无需使用大括号。
library(dplyr, warn.conflicts = FALSE)
mtcars %>% count(cyl)
#> # A tibble: 3 x 2
#> cyl n
#> <dbl> <int>
#> 1 4 11
#> 2 6 7
#> 3 8 14
我很好奇为什么下面的代码不能运行。我认为点 .
是一个占位符并将 mtcats
传递给该位置。
table(mtcars$cyl)
mtcars %>% table(.$cyl)
管道%>%
将左边的对象作为第一个参数粘贴到
右边的功能。所以你基本上执行:
table(mtcars, mtcars$cyl)
#> Error in table(mtcars, mtcars$cyl): all arguments must have the same length
正如 agr0naut91 评论的那样,这可以通过使用大括号来解决:
library(magrittr)
mtcars %>% {table(.$cyl)}
#>
#> 4 6 8
#> 11 7 14
只要你想通过管道传输到一个不是管道的函数,它就可以工作
友好的,这通常意味着它没有 data.frame
参数
作为第一个参数。
使用 dplyr::count()
您可以获得与 base::table()
相当的输出,
无需使用大括号。
library(dplyr, warn.conflicts = FALSE)
mtcars %>% count(cyl)
#> # A tibble: 3 x 2
#> cyl n
#> <dbl> <int>
#> 1 4 11
#> 2 6 7
#> 3 8 14