jalapic
jalapic

Reputation: 14192

printing line breaks using sprintf - with shiny

I'm trying to make line breaks when printing.

here is my code:

temp <- LETTERS[1:11]

print(sprintf("Rank %s = %s \n", 1:11, temp))

output:

[1] "Rank 1 = A \n"  "Rank 2 = B \n"  "Rank 3 = C \n"  "Rank 4 = D \n"  "Rank 5 = E \n"  "Rank 6 = F \n"  "Rank 7 = G \n"  "Rank 8 = H \n"  "Rank 9 = I \n" 
[10] "Rank 10 = J \n" "Rank 11 = K \n"

I naively thought that \n made a line break. My desired output would be:

"Rank 1 = A"  
"Rank 2 = B"  
"Rank 3 = C"  
"Rank 4 = D"  
... etc.

EDIT:

Pascal's comment tells me that it works with cat

cat(sprintf("Rank %s = %s \n", 1:11, temp))

I'm using this code inside of renderText inside shiny. print will return text, but I cannot get cat to return text.

In this case, is there anywhere to generate the required line breaks, without using cat?

Upvotes: 11

Views: 10863

Answers (2)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84519

You can use cat in a renderPrint statement, to render in the UI with verbatimTextOutput.

Another option is to use HTML with some <br/> to break the lines:

renderUI({
  HTML(paste0(sprintf("Rank %s = %s", 1:11, temp), collapse = "<br/>"))
})

to render in the UI with uiOutput.

Upvotes: 3

Ammar Sabir Cheema
Ammar Sabir Cheema

Reputation: 990

You can use writeLines to introduce line breaks as given below:

temp <- LETTERS[1:11]
writeLines(sprintf("Rank %s = %s", 1:11, temp))
Rank 1 = A
Rank 2 = B
Rank 3 = C
Rank 4 = D
Rank 5 = E
Rank 6 = F
Rank 7 = G
Rank 8 = H
Rank 9 = I
Rank 10 = J
Rank 11 = K

You can also use print with writeLines but it will give you a NULL at the end.

Upvotes: 3

Related Questions