Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid linebreak in R's sprintf("very very long string with line break")?

Tags:

r

printf

I have a very long string inside sprintf(). It's so long that it would be useful (readability) to break it (but only in the source code, not in the output). But whenever I break the long string, it introduces a \n and thus the output has a linebreak as well. How can I break the string in the source code such that it isn't broken in the output?

like image 543
Marius Hofert Avatar asked Jan 19 '15 05:01

Marius Hofert


People also ask

What is \r line break?

CR = Carriage Return ( \r , 0x0D in hexadecimal, 13 in decimal) — moves the cursor to the beginning of the line without advancing to the next line. LF = Line Feed ( \n , 0x0A in hexadecimal, 10 in decimal) — moves the cursor down to the next line without returning to the beginning of the line.

How do you Linebreak a string?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.

How do I print a line break in R?

The most commonly used are "\t" for TAB, "\n" for new-line, and "\\" for a (single) backslash character.


1 Answers

Perhaps something like the following would be useful (though it's hard to tell without knowing what your input strings actually look like or how you intend to use them).

Fmt <- c(" %s is %d feet tall.\n", 
         "%s likes chocolate.\n",
         "%s eats %d bars of chocolate", 
         "every night after dinner.")

sprintf(paste(Fmt, collapse = " "), "Sven", 7, "Sven", "He", 3)
# [1] " Sven is 7 feet tall.\n Sven likes chocolate.\n He eats 3 bars of chocolate every night after dinner."
cat(.Last.value)
#  Sven is 7 feet tall.
#  Sven likes chocolate.
#  He eats 3 bars of chocolate every night after dinner.
like image 92
A5C1D2H2I1M1N2O1R2T1 Avatar answered Nov 12 '22 00:11

A5C1D2H2I1M1N2O1R2T1