在 R 中将点-点-点 (`...`) 与 `str_replace_all()` 结合使用

问题描述 投票:0回答:1

我有一个函数,它是

stringr::str_c()
的包装器,因此使用
...
参数接收任意数量的字符向量作为输入。 问题是我想在将这些向量传递给
stringr::str_replace_all()
之前用
str_c()
对这些向量进行一些初步清理,但是
str_replace_all()
函数只接收一个字符向量作为字符串输入。

如何将

...
参数传递给 str_replace all()?

请注意,我打算稍后在我的函数中使用

...
的替换版本,因此替换的结果应该以某种方式保存在可以传递给
str_c()
的表格中。

我收到的一个答案这里是这样的:

这是不雅的,因为它迫使论点得以实现,但正如您所描述的问题,它完成了工作:

library(stringr)

f <- function(...) {
  unlist(list(...)) |> 
    str_replace_all("z", "0") |> 
    str_c()
}

f('az', 'bz', 'cz')  # "a0" "b0" "c0"

这确实有效,但也确实不够优雅。我想找到一种在没有意识到参数的情况下执行此操作的方法。有什么想法吗?

谢谢!

r functional-programming stringr tidyeval
1个回答
2
投票

使用

lapply()
str_replace_all()
映射到捕获的
...
上,然后使用
do.call()
将所有元素传递给
str_c()

library(stringr)

str_replace_all_c <- function(..., pattern, replacement) {
  list(...) |>
    lapply(str_replace_all, pattern, replacement) |>
    do.call(what = str_c)
}

v1 <- c("I_am_", "of_a_modern_")
v2 <- c("the_very_model_", "Major-General")

str_replace_all_c(v1, v2, pattern = "_", replacement = " ")
# "I am the very model "      "of a modern Major-General"

使用 tidyverse 函数,等价于:

library(stringr)
library(purrr)
library(rlang)

str_replace_all_c <- function(..., pattern, replacement) {
  dots <- map(
    list2(...),
    \(x) str_replace_all(x, pattern, replacement)
  )
  exec(str_c, !!!dots)
}

请注意,如果向量的长度 >1,您之前得到的答案将无效;使用

unlist()
将它们全部组合成一个向量,因此在传递给
str_c()
时它们不会连接在一起。

© www.soinside.com 2019 - 2024. All rights reserved.