Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printing line breaks using sprintf - with shiny

Tags:

r

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?

like image 824
jalapic Avatar asked Feb 27 '15 04:02

jalapic


2 Answers

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.

like image 83
Ammar Sabir Cheema Avatar answered Sep 18 '22 02:09

Ammar Sabir Cheema


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.

like image 33
Stéphane Laurent Avatar answered Sep 19 '22 02:09

Stéphane Laurent