有没有办法改变像 paste 这样的函数中参数的顺序,它按顺序接受向量,以使其与管道运算符兼容?

Is there a way to change the order of arguments in functions like paste, which take vectors in an order, to make it compatible with piping operators?

我有一长串使用管道的代码,这些代码以要提交给 paste() 的参数结束。像这样

"string1" %>% paste ("string2", sep = "_")

结果为“string1_string2”。但是我想要“string2_string1”。除了保存变量和 运行 一个新命令之外,还有其他解决方案吗? stringr 包中有解决方案吗?

您可以使用 . 作为管道值的占位符。

"string1" %>% paste("string2", ., sep = "_")
#[1] "string2_string1"

同样适用于 stringr::str_c -

"string1" %>% stringr::str_c("string2", ., sep = "_")
#[1] "string2_string1"

我们可以使用base R (R 4.1.0)

"string1" |>
    {\(x) paste("string2", x, sep = "_")}()
[1] "string2_string1"