rprintf:字符串、向量和列表的格式化

rprintf:字符串、向量和列表的格式化

本文是rprintf包的参考文档rprintf.pdf的学习笔记。该包提供的rprintf()函数可以用于字符串、向量和列表的格式化。这些功能类似与Python中的格式化输出。

安装

R
1
install.packages("rprintf")

使用

直接对字符串进行格式化

R
1
2
3
4
5
6
7
8
> library(rprintf)
> rprintf('Hello, %s', 'world')
[1] "Hello, world"
> rprintf('%s (%d years old)', 'Ken', 24)
[1] "Ken (24 years old)"
> # 数字可以设定输出格式
> rprintf('He is %d but has a height of %.1fcm', 18, 190)
[1] "He is 18 but has a height of 190.0cm"

使用变量进行字符串格式化

R
1
2
3
4
5
6
7
8
9
> rprintf('Hello, $name', name = 'world')
[1] "Hello, world"
> # 这样的话比paste()和paste0()好用多了
> (str = rprintf('$name, ($age years old)', name = 'Ken', age = 24))
[1] "Ken, (24 years old)"
> rprintf("He is $age but has a height of $height:.2fcm", age = 18, height = 190)
[1] "He is 18 but has a height of 190.00cm"
> rprintf('$a, $b:.1f, $c:+.2f, $b, $a:.0f', a = 1, b = 2.34, c = 3.78)
[1] "1, 2.3, +3.78, 2.34, 1"

使用索引进行字符串格式化

R
1
2
3
4
5
6
7
8
9
10
> rprintf('Hello, {1}', 'world')
[1] "Hello, world"
> rprintf('{1} ({2} years old)', 'Ken', 24)
[1] "Ken (24 years old)"
> rprintf('He is {1} but has a height of {2:.2f}cm', 18, 190)
[1] "He is 18 but has a height of 190.00cm"
> rprintf('{1}, {2:.1f}, {3:.2f}, {2}, {1:.0f}', 1.56, 2.34, 3.78)
[1] "1.56, 2.3, 3.78, 2.34, 2"
> rprintf('{2}, {1}', 'x', 'y')
[1] "y, x"

也可以用于向量和列表的格式化

R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
> rprintf(c('%s:%d', '$name:$age', '{1}:{2}'), name = 'Ken', age = 24)
[1] "Ken:24" "Ken:24" "Ken:24"
> rprintf(c(a = '%s:%d', b = '$name:$age', c = '{1}:{2}'), name = 'Ken', age = 24)
a b c
"Ken:24" "Ken:24" "Ken:24"
> rprintf(list('%s:%d', '$name:$age', '{1}:{2}'), name = 'Ken', age = 24)
[[1]]
[1] "Ken:24"

[[2]]
[1] "Ken:24"

[[3]]
[1] "Ken:24"

> rprintf(list(a = '%s:%d', b = '$name:$age', c = '{1}:{2}'), name = 'Ken', age = 24)
$a
[1] "Ken:24"

$b
[1] "Ken:24"

$c
[1] "Ken:24"

还可以以列表的形式传递参数

R
1
2
3
4
5
> p <- list(name = 'Ken', age = 24)
> rprintf('name: $name, age: $age', p)
[1] "name: Ken, age: 24"
> rprintf('name: {1}, age: {2}', p)
[1] "name: Ken, age: 24"
# R

评论

程振兴

程振兴 @czxa.top
截止今天,我已经在本博客上写了636.8k个字了!

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×