如何从变量创建字符串?

时间:2018-07-12 13:59:15

标签: r string

在R中,我想使用存储的值创建一个字符串。在Python中,我将使用f-strings来提高可读性。

>>> a_val = 1
>>> b_val = 99

>>> fname_python = f'a{a_val}_b{b_val}.csv'
>>> fname_python
a1_b99.csv

我在R中找到了两种方法来做到这一点,(1)paste和(2)sprintf

a_val <- 1
b_val <- 99

# paste and collapse are best when you have an existing vector
# fname1 <- paste(c('a', a_val, '_b', b_val, '.csv'), collapse = '')  
# paste0 is better in this example
fname1 <- paste0('a', a_val, '_b', b_val, '.csv')
# 'a1_b99.csv'

fname2 <- sprintf('a%d_b%d.csv', a_val, b_val)
# 'a1_b99.csv'

是否还有更多类似于Python的f字符串?

1 个答案:

答案 0 :(得分:6)

一个选项是Wickham的tidyverse的Jim Hester的glue库。

来自the Github README的示例:

library(glue)

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