Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print backslash in R strings

Tags:

r

knitr

GNU R 3.02

> bib <- "\cite"
Error: '\c' is an unrecognized escape in character string starting ""\c"
> bib <- "\\cite"
> print(bib)
[1] "\\cite"
> sprintf(bib)
[1] "\\cite"
> 

how can I print out the string variable bib with just one "\"?

(I've tried everything conceivable, and discover that R treats the "\\" as one character.)

I see that in many cases this is not a problem, since this is usually handled internally by R, say, if the string were to be used as text for a plot.

But I need to send it to LaTeX. So I really have to remove it.

I see cat does the trick. If cat could only be made to send its result to a string.

like image 641
Rolf Marvin Bøe Lindgren Avatar asked Oct 12 '13 11:10

Rolf Marvin Bøe Lindgren


People also ask

How do you backslash in R string?

In R (and elsewhere), the backslash is the “escape” symbol, which is followed by another symbol to indicate a special character. For example, "\t" represents a “tab” and "\n" is the symbol for a new line (hard return).

How do I print backslash in printf?

We will discuss the C program to understand How to Print backslash(\) It is very easy, we just have to use “\\” format specifier withing printf(), for printing backslash(\), on the output screen.

How do you print double backslash?

To print a "\", use \backslash in math mode and \textbackslash in text mode. To print "\\", use the command twice.


1 Answers

You should use cat.

bib <- "\\cite"
cat(bib)
# \cite

You can remove the ## and [1] by setting a few options in knitr. Here is an example chunk:

<<newChunk,echo=FALSE,comment=NA,background=NA>>=
bib <- "\\cite"
cat(bib)
@

which gets you \cite. Note as well that you can set these options globally.

like image 50
nograpes Avatar answered Sep 23 '22 20:09

nograpes