r - 用向量替换部分字符串
问题描述
我在用一组向量替换替换单个字符串的部分以产生向量时遇到问题。
我有一个字符串tex
,旨在告诉图表要放置哪些文本作为节点(和其他)标签。
因此,如果tex
is"!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() 也不这样做。
解决方案
可能的 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 )
将给出相同的结果。
推荐阅读
- xcode - 如何在 Xcode 中解决此构建问题?
- python - 我怎样才能等待所有进程完成然后做某事?
- python - SnowflakeSQLException 错误代码:390100,消息:指定的用户名或密码不正确
- reactstrap - 反应带
固定在顶部 - javascript - CSS 网格在下一页视图中被破坏
- python - eventthub中的分区是什么?
- python - 如何使用 RegEx 从 html 文档中提取信息
- java - 有没有办法在 Eclipse 中告诉 Maven 在哪里部署创建的 .war 或 .jar 文件?
- java - app.props 中定义的活动配置文件但是环境变量返回活动配置文件的空数组
- java - 我正在使用 resttemplate 调用 API,但我得到了 UnsupportedOperationsException