rstringr-markdownsavecat

Is there a way to save text in R without it actively implementing \n?


I'm trying to use a handful of smaller functions to generate input for R Markdown. Some of the input for R Markdown contains calls like: cat("\\centering\n") or cat(Obj1, Obj2, Obj3, "\n")

Is there a simple way of telling R not to act on \n? I've tried using both write.table() and cat() to save the text, and both will instead act on the \n and save:

cat("\\centering
")
cat(Obj1, Obj2, Obj3, "
")

I want to be able to save the whole thing including the line break.

These are the exact arguments I've tried:

write.table(x = string, file = FileName, col.names = F, row.names = F, eol="")
write.table(x = string, file = FileName, col.names = F, row.names = F)
cat(string, file = FileName)

[EDIT] To add more context, I'm working with confidential information (both mathematical models and person information), so I can't give actual code specifics. The idea is to use a private package to generate an R Markdown template. I have the original RMD template, and the only thing currently breaking is when I have to save \n. So, for example, the RMD template I'm trying to recreate has cat("\\centering\n") written inside it. Trying to pass \\\\n has not changed the behavior when saving it:

string = cat("\\centering\\\\n")
cat(string, file = file.rmd)
View(file.rmd): cat("\\centering
            ")

When I open file.rmd, I want the result to be: cat("\\centering\n")


Solution

  • If you don't like the \n to be treated as a newline, you have to escape it, using \, e.g.

    > cat("centering\n") # no escape returns centering + newline
    centering
    
    > cat("\\centering\n") # escaping the \ before centering returns \centering + newline
    \centering
    
    > cat("\\centering\\n") # escaping both the \ before centering and before the \n returns \centering without newline
    \centering\n>
    

    You might apply an escaping \ to all newlines symbols, i.e. using gsub():

    > gsub("\n", "\\\\n", string)
    [1] "\\centering\\n"
    

    Note that 4 \ are used to create a \\n because we need to escape each \ when substituting it, cp. this link, section Escaping, for more info on the topic.

    EDIT

    The output of gsub should overwrite the object which is being modified, or you should create another variable that will be used for exporting.

    For example:

    > string <- "\\centering\n"
    > new_string <- gsub("\n", "\\\\n", string) # either create a new variable
    > string <- gsub("\n", "\\\\n", string) or overwrite the existing one
    

    As per the other affected words it is always possible to specify an appropriate gsub to correct for it:

    > string <- c("\\centering\n", "\newline", "\\anotherstring\n", "\anotherone\n")
    > new_string <- gsub("\n", "\\\\n", string) # fixing string
    > new_string <- gsub("\\\\newline", "\\\newline", new_string) # re-writing new_string with correct version of \newline