[R] Pesky file encoding problem

Duncan Murdoch murdoch.duncan at gmail.com
Mon Nov 7 02:07:08 CET 2016


On 06/11/2016 12:25 PM, Joshua Banta wrote:
> Dear everyone,
>
> Please consider the following code, which I am using to make a custom text file. (I need to build the text file line-by-line like this for some idiosyncratic reasons that I will not get into here. But basically the real text file I am making is longer and more complicated than this.)
>
> outfile = "output.arp"
> cat('Title="data"', file=outfile, append=FALSE, sep = "\r\n")
> cat('DataType=DNA', file=outfile, append=TRUE, sep = "\r\n")
> cat('GenotypicData=1', file=outfile, append=TRUE, sep = "\r\n")
> cat('GameticPhase=0', file=outfile, append=TRUE, sep = "\r\n")
> cat('LocusSeparator=WHITESPACE', file=outfile, append=TRUE, sep = "\r\n")
> cat("", file=outfile, append=TRUE, sep = "\r\n")
> cat("[Data]", file=outfile, append=TRUE, sep = "\r\n")
> cat("[[Samples]]", file=outfile, append=TRUE, sep = “")
>
> Here is my question:
>
> When the output file (output.arp) is opened using TextEdit on a Mac, each line is shown separated by one or more carriage returns, which is what I want. When the output file is opened using Notepad on a PC, each line of text runs into the next with no carriage returns, which is not what I want.
>
> How can I make this text file, or convert it, in such a way that it will open on Notepad on a PC showing each line separated by one or more carriage returns?
>
> I am aware of solutions to this problem using other software as an intermediary, such as TextWrangler, but I would like to accomplish this entirely using r itself.
>
> I would be most appreciative of the full code needed to get the job done.

Notepad is a really weak text editor.  If you want it to recognize line 
breaks, they need to be in Windows style.

Even though your "sep" argument looks like Windows CR/LF, it is never 
used except to change the behaviour of cat, which will write a single \n 
after each entry.  (See the note in ?cat that explains this strange 
behaviour.)

So what you could do is something like this:

crlf <- "\r\n"
outfile = "output.arp"
cat('Title="data"', crlf, file=outfile, append=FALSE)
cat('DataType=DNA', crlf, file=outfile, append=TRUE)

etc.

Duncan Murdoch



More information about the R-help mailing list