當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


R stringr str_interp 字符串插值

[Superseded]

str_interp()str_glue() 取代。

字符串插值是指定字符串的有用方法,該字符串取決於特定環境中的值。它允許創建字符串,與使用例如相比,它更容易讀寫。 paste()sprintf() 。 (模板)字符串可以包含 ${expression}$[format]{expression} 形式的表達式占位符,其中表達式是可以在給定環境中計算的有效 R 表達式,而 format 是可與 sprintf() 一起使用的有效格式規範。

用法

str_interp(string, env = parent.frame())

參數

string

模板字符串。此函數未矢量化:字符向量將折疊為單個字符串。

env

評估表達式的環境。

內插字符串。

也可以看看

str_glue()str_glue_data() 用於解決同一問題的替代方法。

作者

斯特凡·米爾頓·巴奇

例子


# Using values from the environment, and some formats
user_name <- "smbache"
amount <- 6.656
account <- 1337
str_interp("User ${user_name} (account $[08d]{account}) has $$[.2f]{amount}.")
#> [1] "User smbache (account 00001337) has $6.66."

# Nested brace pairs work inside expressions too, and any braces can be
# placed outside the expressions.
str_interp("Works with } nested { braces too: $[.2f]{{{2 + 2}*{amount}}}")
#> [1] "Works with } nested { braces too: 26.62"

# Values can also come from a list
str_interp(
  "One value, ${value1}, and then another, ${value2*2}.",
  list(value1 = 10, value2 = 20)
)
#> [1] "One value, 10, and then another, 40."

# Or a data frame
str_interp(
  "Values are $[.2f]{max(Sepal.Width)} and $[.2f]{min(Sepal.Width)}.",
  iris
)
#> [1] "Values are 4.40 and 2.00."

# Use a vector when the string is long:
max_char <- 80
str_interp(c(
  "This particular line is so long that it is hard to write ",
  "without breaking the ${max_char}-char barrier!"
))
#> [1] "This particular line is so long that it is hard to write without breaking the 80-char barrier!"
源代碼:R/interp.R

相關用法


注:本文由純淨天空篩選整理自Hadley Wickham等大神的英文原創作品 String interpolation。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。