str_interp()
被 str_glue()
取代。
字符串插值是指定字符串的有用方法,該字符串取決於特定環境中的值。它允許創建字符串,與使用例如相比,它更容易讀寫。 paste()
或 sprintf()
。 (模板)字符串可以包含 ${expression}
或 $[format]{expression}
形式的表達式占位符,其中表達式是可以在給定環境中計算的有效 R 表達式,而 format
是可與 sprintf()
一起使用的有效格式規範。
也可以看看
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 stringr str_which 查找匹配索引
- R stringr str_extract 提取完整的匹配項
- R stringr str_subset 查找匹配元素
- R stringr str_escape 轉義正則表達式元字符
- R stringr str_trim 刪除空格
- R stringr str_sub 使用子字符串的位置獲取和設置子字符串
- R stringr str_replace_na 把NA變成“NA”
- R stringr str_trunc 將字符串截斷至最大寬度
- R stringr str_match 從匹配中提取組件(捕獲組)
- R stringr str_like 以與 SQL 的 LIKE 運算符相同的方式檢測模式
- R stringr str_length 計算長度/寬度
- R stringr str_detect 檢測是否存在匹配
- R stringr str_count 計算匹配次數
- R stringr str_split 將字符串分成幾段
- R stringr str_unique 刪除重複的字符串
- R stringr str_remove 刪除匹配的模式
- R stringr str_pad 將字符串填充到最小寬度
- R stringr str_equal 判斷兩個字符串是否相等
- R stringr str_view 查看字符串和匹配項
- R stringr str_glue 用膠水插補
- R stringr str_conv 指定字符串的編碼
- R stringr str_order 對字符向量進行排序、排名或排序
- R stringr str_starts 檢測開始/結束時是否存在匹配
- R stringr str_c 將多個字符串連接成一個字符串
- R stringr str_wrap 將單詞包裝成格式良好的段落
注:本文由純淨天空篩選整理自Hadley Wickham等大神的英文原創作品 String interpolation。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。