字符串填充与对齐
使用 formatC() 和 format() 输出定宽且对齐的文本
字符串填充与对齐 是 CoddyKit 上的免费 R Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 R Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 R Academy 课程共包含 4 节课。
字符串填充为何重要
固定宽度输出对于纯文本表格、日志文件和报告至关重要。R 提供了 formatC() 和 format(),用于将值填充到固定宽度,确保列在等宽字体显示中正确对齐。
# Unformatted: columns misalign
cat('Alice 85\n')
cat('Bob 9200\n')
# Padded: columns align
cat(formatC('Alice', width = 10), formatC(85, width = 6), '\n')
cat(formatC('Bob', width = 10), formatC(9200, width = 6), '\n')formatC() — 右对齐填充
formatC(x, width = n) 会将值填充到至少 n 个字符的宽度,默认采用右对齐。空格会添加在左侧。数字和字符串都可以使用此方法。
formatC('hi', width = 10)
formatC(42, width = 10)
formatC(3.14, width = 10)使用 flag 让 formatC() 左对齐
flag = '-' 参数会切换为左对齐,并在右侧用空格填充。这非常适合表格列中的字符串标签,尤其是在您希望值从左边缘开始时。
items <- c('Pen', 'Notebook', 'Stapler')
prices <- c(1.5, 4.99, 7.25)
for (i in seq_along(items)) {
cat(formatC(items[i], width = 12, flag = '-'),
formatC(prices[i], format = 'f', digits = 2, width = 8),
'\n')
}使用数值格式调用 formatC()
formatC() 支持以下格式代码:'f' 表示定点小数,'e' 表示科学计数法,'g' 表示在两者中选择更短的表示形式,'d' 表示整数。digits 参数控制精度。
x <- 12345.6789
formatC(x, format = 'f', digits = 2)
formatC(x, format = 'e', digits = 3)
formatC(x, format = 'g', digits = 5)
formatC(42L, format = 'd', width = 8)format() — Base R 对齐
format(x, width = n, justify = 'left'/'right'/'centre') 是通用的对齐函数。它适用于任意 R 对象,并返回一个由等宽字符串组成的字符向量。数字默认右对齐,字符串默认左对齐。
words <- c('cat', 'elephant', 'ox')
format(words, width = 10)
format(words, width = 10, justify = 'right')使用 format() 控制数值精度
format() 还可以使用 nsmall 控制小数位数(小数点后的最少位数),并使用 big.mark 添加千位分隔符。这些功能非常适合显示财务数据。
format(1234567.8, big.mark = ',', nsmall = 2)
format(0.1, nsmall = 4)
format(c(1.5, 100, 0.005), nsmall = 3)strrep() — 重复字符串
strrep(x, times) 会将字符串重复指定次数。您可以使用它构建分隔线、填充字符串或视觉装饰,而不必手动连接字符。
strrep('-', 40)
strrep('=-', 20)
strrep(c('ab', 'cd'), c(3, 2))
# Draw a simple table border
cat(strrep('=', 30), '\n')构建固定宽度文本表格
将 formatC()、cat() 和 strrep() 结合起来,可以构建整洁的纯文本表格。这种模式在 CLI 工具和日志文件中很常见。
header <- paste0(formatC('Name', width=12,flag='-'),
formatC('Score', width=8,flag='-'),
formatC('Grade', width=8,flag='-'))
cat(header, '\n')
cat(strrep('-', 28), '\n')
row1 <- paste0(formatC('Alice', width=12,flag='-'),
formatC(92,width=8),formatC('A',width=8,flag='-'))
cat(row1, '\n')formatC() 与 sprintf() 的填充比较
formatC() 和 sprintf() 都可以生成填充后的输出。对于简单情况,sprintf() 更简洁;如果要对整个向量应用相同格式,formatC() 更灵活。
x <- 42
# sprintf approach
sprintf('%10d', x)
sprintf('%-10s', 'hello')
# formatC approach
formatC(x, width = 10)
formatC('hello', width = 10, flag = '-')控制科学计数法
formatC(x, format='e', digits=n) 或 options(scipen=999) 可以控制 R 何时切换到科学计数法。scipen 选项表示惩罚值;值越大,R 在切换前抑制科学计数法的时间越长。
# Default scipen
print(0.0001234)
print(1234567890)
# Force scientific
formatC(0.0001234, format = 'e', digits = 3)
# Suppress scientific globally
old <- options(scipen = 999)
print(0.0001234)
options(old)实践:填充 ID 和标签
在报告中,经常需要使用零填充的 ID 或左侧填充的标签。formatC() 可以处理这两种情况:对数字使用 flag = '0' 进行零填充,对字符串使用 flag = '-' 进行左对齐。
ids <- c(1, 12, 123)
names <- c('Alice', 'Bob', 'Carol')
scores <- c(88.5, 91.0, 76.25)
for (i in seq_along(ids)) {
cat(formatC(ids[i], width=5, format='d', flag='0'),
formatC(names[i], width=10, flag='-'),
formatC(scores[i], width=8, format='f', digits=2),
'\n')
}快速检查
formatC() 的哪个参数可以使输出在指定宽度内左对齐?
填充与对齐:要点总结
字符串填充与对齐的要点:
formatC(x, width=n)将内容填充到宽度 n 并右对齐;flag='-'可实现左对齐formatC(x, format='f', digits=2)用于定点小数;'e'用于科学计数法format(x, justify='left'/'right'/'centre')用于通用对齐format(x, big.mark=',', nsmall=2)用于千位分隔符和末尾小数位strrep(s, n)将字符串重复 n 次,非常适合生成分隔线- 与
cat()结合使用可输出纯文本表格
cat(strrep('=', 30), '\n')
cat(formatC('Item', width=12, flag='-'),
formatC('Price', width=10), '\n')
cat(strrep('-', 30), '\n')
cat(formatC('Apple', width=12, flag='-'),
formatC(1.99, width=10, format='f', digits=2), '\n')常见问题解答
「字符串填充与对齐」课时是免费的吗?
是的 — 「字符串填充与对齐」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 R Academy 课程的其余内容,请升级到 CoddyKit PRO。 R Academy 课程共包含 4 节课。
「字符串填充与对齐」这节课中我会学到什么?
使用 formatC() 和 format() 输出定宽且对齐的文本 你通过在浏览器中直接运行的动手代码来练习 R Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 R Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 R Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「字符串填充与对齐」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 R Academy 课中编写并运行代码吗?
能。每节 R Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。