Remi.b Remi.b - 2 months ago 8
R Question

What are the standard tools to align printed strings in R?

Here is a series of

cat
statements

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


How would I do to align them like this

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


or like this

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


or eventually like this

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

Answer

Try this:

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

with output:

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