用变量值替换字符串中的变量名 [R]
Replace variable name in string with variable value [R]
我在R中有一个角色,比如说"\frac{A}{B}"
。我有 A
和 B
的值,比如 5
和 10
。有没有办法可以用 5
和 10
替换 A
和 B
?
我尝试了以下方法。
words <- "\frac{A}{B}"
numbers <- list(A=5, B=10)
output <- do.call("substitute", list(parse(text=words)[[1]], numbers))
但我在 \
上收到错误消息。有什么办法可以做到这一点?我试图用实际变量值创建方程式。
我对 gsub
比 substitute
更熟悉。以下作品:
words <- "\frac{A}{B}"
numbers <- list(A=5, B=10)
arglist = mapply(list, as.list(names(numbers)), numbers, SIMPLIFY=F)
for (i in 1:length(arglist)){
arglist[[i]]["x"] <- words
words <- do.call("gsub", arglist[[i]])
}
但这当然是不安全的,因为您正在迭代替换。例如,如果第一个变量的值为 "B" 而第二个变量的名称为 "B",您就会遇到问题。可能有更简洁的方法。
试试这个:
sprintf(gsub('\{\w\}','\{%d}',words),5,10)
您可以使用 stringi 函数 stri_replace_all_fixed()
stringi::stri_replace_all_fixed(
words, names(numbers), numbers, vectorize_all = FALSE
)
# [1] "\frac{5}{10}"
我在R中有一个角色,比如说"\frac{A}{B}"
。我有 A
和 B
的值,比如 5
和 10
。有没有办法可以用 5
和 10
替换 A
和 B
?
我尝试了以下方法。
words <- "\frac{A}{B}"
numbers <- list(A=5, B=10)
output <- do.call("substitute", list(parse(text=words)[[1]], numbers))
但我在 \
上收到错误消息。有什么办法可以做到这一点?我试图用实际变量值创建方程式。
我对 gsub
比 substitute
更熟悉。以下作品:
words <- "\frac{A}{B}"
numbers <- list(A=5, B=10)
arglist = mapply(list, as.list(names(numbers)), numbers, SIMPLIFY=F)
for (i in 1:length(arglist)){
arglist[[i]]["x"] <- words
words <- do.call("gsub", arglist[[i]])
}
但这当然是不安全的,因为您正在迭代替换。例如,如果第一个变量的值为 "B" 而第二个变量的名称为 "B",您就会遇到问题。可能有更简洁的方法。
试试这个:
sprintf(gsub('\{\w\}','\{%d}',words),5,10)
您可以使用 stringi 函数 stri_replace_all_fixed()
stringi::stri_replace_all_fixed(
words, names(numbers), numbers, vectorize_all = FALSE
)
# [1] "\frac{5}{10}"