我希望将定义的变量插入到 R 中的字符串中,其中变量将插入多个位置。
我已经看到sprintf可能有用。
所需输入的示例:
a <- "tree"
b <- sprintf("The %s is large but %s is small. %s", a)
Run Code Online (Sandbox Code Playgroud)
理想的输出将返回
"The tree is large but tree is small. tree"
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用这样的功能:
b <- sprintf("The %s is large but %s is small. %s",a,a,a)
Run Code Online (Sandbox Code Playgroud)
但是,对于我的实际工作,我需要插入 10 次以上,因此我正在寻找更清洁/更简单的解决方案。
gsub 会是更好的解决方案吗?
我的确切问题已在此处得到解答,但它是针对 Go 语言的:
sin*_*dur 11
这是一个实际的 sprintf() 解决方案:
a <- "tree"
sprintf("The %1$s is large but %1$s is small. %1$s", a)
[1] "The tree is large but tree is small. tree"
Run Code Online (Sandbox Code Playgroud)
官方 sprintf() 文档中有更多示例。
1) do.call使用do.call参数a可以使用 来构造rep。没有使用任何包。
a <- "tree"
s <- "The %s is large but %s is small. %s"
k <- length(gregexpr("%s", s)[[1]])
do.call("sprintf", as.list(c(s, rep(a, k))))
## [1] "The tree is large but tree is small. tree"
Run Code Online (Sandbox Code Playgroud)
2) gsub这已经在评论中提到了,但gsub可以使用。同样,没有使用任何包。
gsub("%s", a, s, fixed = TRUE)
## [1] "The tree is large but tree is small. tree"
Run Code Online (Sandbox Code Playgroud)
3)gsubfn gsubfn包支持准perl风格的字符串插值:
library(gsubfn)
a <- "tree"
s2 <- "The $a is large but $a is small. $a"
fn$c(s2)
## [1] "The tree is large but tree is small. tree"
Run Code Online (Sandbox Code Playgroud)
此外,反引号可用于括起要计算和替换的整个 R 表达式。
这可以与任何函数一起使用,而不仅仅是c产生非常紧凑的代码。例如假设我们要计算替换s 后的字符数。那么可以这样做:
fn$nchar(s2)
## [1] 38
Run Code Online (Sandbox Code Playgroud)
4) $n 格式符号 在sprintf符号中指%n$的是以下第 n 个参数fmt:
a <- "tree"
s <- "The %1$s is large but %1$s is small. %1$s"
sprintf(s, a)
## [1] "The tree is large but tree is small. tree"
Run Code Online (Sandbox Code Playgroud)