使用 magrittr Piper 运算符,我们对向量进行操作。
strings <- "a b c"
strings %>% strsplit(" ") # Here we get a list
> strings %>% strsplit(" ")
[[1]]
[1] "a" "b" "c"
Run Code Online (Sandbox Code Playgroud)
但假设我们只想获取此列表的单个元素。这需要我们(获取第一个元素的示例):
(strings %>% strsplit(" "))[[1]][1] # Notice the braces around the expression..
Run Code Online (Sandbox Code Playgroud)
现在我的问题是:有没有一种方法可以使用管道运算符而不需要将整个表达式放在大括号中?我认为,如果我们不必将其写入临时变量或使用括号而是使用某种特殊的管道运算符,那么它会更加透明。
还有其他方法可以做到这一点吗?
或者也可以:
strings %>% strsplit(" ") %>% { .[[1]][1] }
这将是相同的
strings %>% strsplit(" ") %>% .[[1]] %>% .[1]
比较一下时间:
library(purrr)
library(dplyr)
microbenchmark::microbenchmark(
(strings %>% strsplit(" ") %>% unlist %>% first)
,(strings %>% strsplit(" ") %>% { .[[1]][1] })
,(strings %>% strsplit(" ") %>% map_chr(1))
)
# Unit: microseconds
# expr min lq mean median uq max neval
# (strings %>% strsplit(" ") %>% unlist %>% first) 280.270 288.363 301.9581 295.4685 305.1395 442.511 100
# (strings %>% strsplit(" ") %>% { .[[1]][1] }) 211.980 219.875 229.4866 226.3875 235.6640 298.429 100
# (strings %>% strsplit(" ") %>% map_chr(1)) 682.123 693.965 747.1690 710.1495 752.3875 2578.091 100
Run Code Online (Sandbox Code Playgroud)