r - 在 R 中对齐打印字符串的标准工具是什么?

标签 r string printing alignment cat

这是一系列cat语句

words = c("Hello","bar","ROCKnROLL","R","Supercalifragilisticexpialidocious")
for (i in 1:length(words))
{
    cat(paste0(words[i], "\t: ",nchar(words[i]),"\n"))
}

Hello   : 5
bar : 3
ROCKnROLL   : 9
R   : 1
Supercalifragilisticexpialidocious  : 34

我该怎么做才能像这样对齐它们

Hello                               : 5
bar                                 : 3
ROCKnROLL                           : 9
R                                   : 1
Supercalifragilisticexpialidocious  : 34

或者像这样

                             Hello  : 5
                               bar  : 3
                         ROCKnROLL  : 9
                                 R  : 1
Supercalifragilisticexpialidocious  : 34

或者最终像这样

             Hello                  : 5
              bar                   : 3
           ROCKnROLL                : 9
               R                    : 1
Supercalifragilisticexpialidocious  : 34

最佳答案

试试这个:

words = c("Hello","bar","ROCKnROLL","R","Supercalifragilisticexpialidocious")
for (i in 1:length(words)) {
  print(sprintf("%-40s:%d", words[i], nchar(words[i])))
}

输出:

[1] "Hello                                   :5"
[1] "bar                                     :3"
[1] "ROCKnROLL                               :9"
[1] "R                                       :1"
[1] "Supercalifragilisticexpialidocious      :34"

关于r - 在 R 中对齐打印字符串的标准工具是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39536112/

相关文章:

RStudio 语法格式 - 粗体函数名称

c - 将字符串传递给 C 中的函数

java - 根据 If 语句切换变量

android - 通过 USB 使用 android 从打印机获取打印

r - 在 R Shiny 中处理输入数据集

regex - 如何使用正则表达式和R正确编辑字符串?

r - 如何在没有引用值的情况下从 R 编写 csv?

PHP 用字符串替换类函数

netbeans - 在 NetBeans 中打印项目

Delphi Word自动化-打印合并文档