当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R stringr str_glue 用胶水插补


这些函数是 glue::glue()glue::glue_data() 的包装器,它们提供了强大而优雅的语法,用于使用 {} 插入字符串。

这些包装器提供了一小部分完整选项。直接从glue 中使用glue()glue_data() 进行更多控制。

用法

str_glue(..., .sep = "", .envir = parent.frame())

str_glue_data(.x, ..., .sep = "", .envir = parent.frame(), .na = "NA")

参数

...

[expressions]
未命名的参数被视为要格式化的表达式字符串。多个输入在格式化之前连接在一起。命名参数被视为可用于替换的临时变量。

.sep

[character(1):‘“”’]
分隔符用于分隔元素。

.envir

[environmentparent.frame()]
计算每个表达式的环境。表达式从左到右计算。如果.x是一个环境,表达式在该环境中求值并且.envir被忽略。如果NULL通过了,就相当于emptyenv().

.x

[listish]
用于查找值的环境、列表或 DataFrame 。

.na

[character(1):‘不适用’]
要替换的值NA值与.如果NULL缺失值被传播,即NA结果会导致NA输出。否则该值将被替换为.na.

与最长输入长度相同的字符向量。

例子

name <- "Fred"
age <- 50
anniversary <- as.Date("1991-10-12")
str_glue(
  "My name is {name}, ",
  "my age next year is {age + 1}, ",
  "and my anniversary is {format(anniversary, '%A, %B %d, %Y')}."
)
#> My name is Fred, my age next year is 51, and my anniversary is Saturday, October 12, 1991.

# single braces can be inserted by doubling them
str_glue("My name is {name}, not {{name}}.")
#> My name is Fred, not {name}.

# You can also used named arguments
str_glue(
  "My name is {name}, ",
  "and my age next year is {age + 1}.",
  name = "Joe",
  age = 40
)
#> My name is Joe, and my age next year is 41.

# `str_glue_data()` is useful in data pipelines
mtcars %>% str_glue_data("{rownames(.)} has {hp} hp")
#> Mazda RX4 has 110 hp
#> Mazda RX4 Wag has 110 hp
#> Datsun 710 has 93 hp
#> Hornet 4 Drive has 110 hp
#> Hornet Sportabout has 175 hp
#> Valiant has 105 hp
#> Duster 360 has 245 hp
#> Merc 240D has 62 hp
#> Merc 230 has 95 hp
#> Merc 280 has 123 hp
#> Merc 280C has 123 hp
#> Merc 450SE has 180 hp
#> Merc 450SL has 180 hp
#> Merc 450SLC has 180 hp
#> Cadillac Fleetwood has 205 hp
#> Lincoln Continental has 215 hp
#> Chrysler Imperial has 230 hp
#> Fiat 128 has 66 hp
#> Honda Civic has 52 hp
#> Toyota Corolla has 65 hp
#> Toyota Corona has 97 hp
#> Dodge Challenger has 150 hp
#> AMC Javelin has 150 hp
#> Camaro Z28 has 245 hp
#> Pontiac Firebird has 175 hp
#> Fiat X1-9 has 66 hp
#> Porsche 914-2 has 91 hp
#> Lotus Europa has 113 hp
#> Ford Pantera L has 264 hp
#> Ferrari Dino has 175 hp
#> Maserati Bora has 335 hp
#> Volvo 142E has 109 hp
源代码:R/glue.R

相关用法


注:本文由纯净天空筛选整理自Hadley Wickham等大神的英文原创作品 Interpolation with glue。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。