rnewlinelf

Build string with OS-specific newline characters (CRLF, LF, CR) to write it into a database table column


I want to write write a string that contains the usual new line character of R (\n) into a column of a database table.

How can I convert the new line into operating system specific representation (Windows = CR/LF, Linux = LF, Mac = CR...)?

I have learned that R does not provide the operating system specific representation so I have to find a work-around:

Any trial to print/cat the string did fail:

msg <- "I want to have \n a new line"
cat(msg)
# I want to have 
#  a new line

out <- capture.output(cat(msg))
out
# a vector with two elements (one for each row but no new line characters anymore)
# [1] "I want to have " " a new line"

paste(out, collapse = "\n")   # how could I inject the correct new line characters here?
# [1] "I want to have \n a new line"

# welcome endless-loop :-)

Is there any way to let R create the correct new line characters from \n in a string?

PS: I am playing around with the built-in tcltk package and puts but I always end with R "reconverting" the newline into \n... Another "cheat" could be to enclose the \n with quotation marks to read it as if it were one line. I have no idea so far how this could work...


Solution

  • One way to correctly set the new line code in R is to query the operating system. Since both OS X and Linux behave the same way, it's a question of determining whether the operating system is Windows. One way to do this is to interrogate the OS environment variable as follows.

    if(substr(Sys.getenv("OS"),1,7) == "Windows") {
        # set Windows newline
      newLine <- "\r\n"
    }
    else {
        # set non-Windows newline
        newLine <- "\n"
    }
    

    Next use paste() with the newLine object to generate the right characters for new line by operating system.

    paste("my text string on a line",newline,sep="")
    

    regards,

    Len