format() 函数可以将一个数值型向量的各个元素按照统一格式转换为字符型。
比如:
> class(format(1.0))
[1] "character"
但不同于as.character(),format 函数可以控制输出的精度和宽度:
- nsmall 控制非科学记数法显示时小数点后的至少要有的位数
- digits 控制至少要有的有效位数
- width 参数指定至少要有的输出宽度
format(c(pi, pi*10000), digits=8, nsmall=4)
## [1] " 3.1415927" "31415.9265359"
format(1.000, width=6, nsmall=2)
## [1] " 1.00"
sprintf 函数有点类似于py 中的printf 函数,可以可以把一个元素或 一个向量的各个元素按照 C 语言输出格式转换为字符型向量。第一个自变量是 C 语言格式的输出格式字符串,其 中%d 表示输出整数,%f 表示输出实数,%02d 表示输出宽度为 2、不够左填 0 的整数,%6.2f 表示输出宽度为 6、 宽度不足时左填空格、含两位小数的实数,等等。
借助这个功能,我们可以对文件进行一些格式化的命名,比如:
sprintf("tour%03d.jpg", c(1, 5, 10, 15, 100))
## [1] "tour001.jpg" "tour005.jpg" "tour010.jpg" "tour015.jpg" "tour100.jpg"
我们还可以传入多个向量,实现多个数据的格式化处理:
sprintf("%1dx%1d=%2d", 1:5, 5:1, (1:5)*(5:1))
## [1] "1x5= 5" "2x4= 8" "3x3= 9" "4x2= 8" "5x1= 5"
我们可以利用sprintf 实现字符串插值:
name <- " 李明"
tele <- "13512345678"
> sprintf("names: %s, teles: %s", name, tele)
[1] "names: 李明, teles: 13512345678"
stringr 包也提供了专门的函数:
name <- " 李明"
tele <- "13512345678"
str_glue(" 姓名: {name}\n电话号码: {tele}\n")
## 姓名: 李明
## 电话号码: 13512345678
其实如果愿意,paste 函数也可以实现这些~
只不过paste 本身就不能批量处理了:
> sprintf("names: %s, teles: %s", name, tele)
[1] "names: 李明, teles: 13512345678" "names: Tony, teles: 66666666"
ps:sprintf 是基于底层c 开发的,应该使用起来会比paste+apply 要快把。