【问题标题】:Is it possible to format text in R in the same way as python?是否可以像 python 一样在 R 中格式化文本?
【发布时间】:2016-11-08 16:00:31
【问题描述】:

我想知道是否可以像 python 一样在 R 中进行文本解析。

所以python是这样做的:

"Hello World! I am from {country}".format("The Netherlands")

现在我正在 R 中寻找完全相同的东西,或者以相同方式工作的东西。

我正在考虑使用gsub 或类似的东西。但这感觉不对。也许sprintfformat 函数是我需要的。

当然,找到合适的解决方案并不难,但我只是想知道 R 中是否有类似 python 格式的东西。

【问题讨论】:

  • 您将无法完全重现 Python 样式的格式,因为 R 不将 . 视为成员访问运算符,但 this article 可能对您有用。
  • @nrussell 这正是我所期待的。感谢您的文章将很有用。
  • 类似sprintf("Hello World! I am from %s", "The Netherlands") 的东西你在找什么?
  • @dww,确实是这样。将更多地研究 sprintf 函数。谢谢!

标签: r formatting string-formatting


【解决方案1】:

除了sprintf(在评论中提到),您可以使用glue 包:

library(glue)

country <- "The Netherlands"
glue("Hello I am from {country}.")

# or
glue("Hello I am from {country}.", country = "Germany")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-17
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    相关资源
    最近更新 更多