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

Rem*_*i.b 1 printing string r 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
Run Code Online (Sandbox Code Playgroud)

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

Hello                               : 5
bar                                 : 3
ROCKnROLL                           : 9
R                                   : 1
Supercalifragilisticexpialidocious  : 34
Run Code Online (Sandbox Code Playgroud)

或者像这样

                             Hello  : 5
                               bar  : 3
                         ROCKnROLL  : 9
                                 R  : 1
Supercalifragilisticexpialidocious  : 34
Run Code Online (Sandbox Code Playgroud)

或最终喜欢这个

             Hello                  : 5
              bar                   : 3
           ROCKnROLL                : 9
               R                    : 1
Supercalifragilisticexpialidocious  : 34
Run Code Online (Sandbox Code Playgroud)

San*_*Dey 5

试试这个:

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

输出:

[1] "Hello                                   :5"
[1] "bar                                     :3"
[1] "ROCKnROLL                               :9"
[1] "R                                       :1"
[1] "Supercalifragilisticexpialidocious      :34"
Run Code Online (Sandbox Code Playgroud)

  • `for()` 循环是不必要的。`sprintf("%-40s:%d", 单词, nchar(单词))` (2认同)