首页 > 解决方案 > 用向量替换部分字符串

问题描述

我在用一组向量替换替换单个字符串的部分以产生向量时遇到问题。

我有一个字符串tex,旨在告诉图表要放置哪些文本作为节点(和其他)标签。

因此,如果texis"!label has frequency of !frequency" 并且T具有label包含值c("chickens","ducks",...)和其他frequency 值的列c("chickens","ducks",...),则该函数返回一个向量,例如c("Chickens has frequency of 35","Ducks has frequency of 12",...)

更正式地说,问题是:

给定一个 tibbleT和一个字符串tex,返回一个长度为 的向量nrow(T),其中每个元素 =tex但其中tex模式!pattern中的每个出现都被向量化的内容替换T$pattern

我查看了 用模式替换 R 中的字符串并用多个字符串替换向量字符串替换,但它们不适合我的用例。stringr::str_replace() 也不这样做。

标签: rstringrstringi

解决方案


可能的 baseR 解决方案使用sprintf()

animals = c("chickens","ducks") 
frequency = c(35,12)

sprintf( "%s has frequency of %s", animals, frequency)

[1] "鸡的频率为 35" "鸭子的频率为 12"

还,

tex = "%s has frequency of %s"
sprintf( tex, animals, frequency )

将给出相同的结果。


推荐阅读