【问题标题】:replace parts of a string with a vector用向量替换部分字符串
【发布时间】:2019-06-13 10:19:36
【问题描述】:

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

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

所以如果tex"!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",...)

更正式地说,问题是:

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

我看了 Replace string in R with patterns and replacements both vectorsString replacement with multiple string 但它们不适合我的用例。 stringr::str_replace() 也不这样做。

【问题讨论】:

    标签: r stringr stringi


    【解决方案1】:

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

    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 )
    

    将给出相同的结果。

    【讨论】:

      猜你喜欢
      • 2017-04-06
      • 2021-03-25
      • 2012-07-17
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      相关资源
      最近更新 更多