glue 是作为tidyverse 的一部分开发的新函数、数据类和包,具有许多扩展功能。它结合了 paste、sprintf 和以前的其他答案的功能。
tmp <- tibble::tibble(firststring = "GAD", secondstring = "AB")
(tmp_new <- glue::glue_data(tmp, "{firststring},{secondstring}"))
#> GAD,AB
由reprex package (v0.2.1) 于 2019 年 3 月 6 日创建
是的,对于这个问题中的简单示例来说,这有点矫枉过正,但在许多情况下都很强大。 (见https://glue.tidyverse.org/)
与paste 和下面的with 相比的快速示例。 glue 代码更容易输入,看起来也更容易阅读。
tmp <- tibble::tibble(firststring = c("GAD", "GAD2", "GAD3"), secondstring = c("AB1", "AB2", "AB3"))
(tmp_new <- glue::glue_data(tmp, "{firststring} and {secondstring} went to the park for a walk. {firststring} forgot his keys."))
#> GAD and AB1 went to the park for a walk. GAD forgot his keys.
#> GAD2 and AB2 went to the park for a walk. GAD2 forgot his keys.
#> GAD3 and AB3 went to the park for a walk. GAD3 forgot his keys.
(with(tmp, paste(firststring, "and", secondstring, "went to the park for a walk.", firststring, "forgot his keys.")))
#> [1] "GAD and AB1 went to the park for a walk. GAD forgot his keys."
#> [2] "GAD2 and AB2 went to the park for a walk. GAD2 forgot his keys."
#> [3] "GAD3 and AB3 went to the park for a walk. GAD3 forgot his keys."
由reprex package (v0.2.1) 于 2019-03-06 创建