user3298179
user3298179

Reputation: 193

Avoid blank line at end of file when using writeLines

In R: Is it possible to avoid having a blank line at the end of a text file generated by writeLines? If not, is there any other way of generating a text file from within R without having a blank line at the end?

Upvotes: 5

Views: 2408

Answers (2)

Myoch
Myoch

Reputation: 855

I had exactly the same concern (different grid, though) and even your comment of the accept answer (by Konrad) did not work for me.

I found the answer here, and here is the full code:

fileConn = file("mytext.txt")
writeLines(c("line1", "line2", "line3"), sep="\n", fileConn)

#now connect to UNIX server and upload your file
library(ssh)
session=ssh_connect("[email protected]")
scp_upload(session, files="mytext.txt")

#Here is the trick, convert all the Windows extra chars to unix
ssh_exec_wait(session, command="dos2unix mytext.txt")

#Then start your Grid job
ssh_exec_wait(session, command="sbatch mytext.txt")

ssh_disconnect(session)

Upvotes: -1

Konrad Rudolph
Konrad Rudolph

Reputation: 545598

There is no blank line.

R (correctly) ends each line with '\n' (or '\r\n' on Windows). In other words, the file consists of lines, and each line ends with a line break.

Unfortunately, there are many tools (especially on Windows) which treat such files incorrectly and display an extra line at the end. However, that’s a fault with these tools, not with R. Consequently, this shouldn’t be fixed in the R code.

As a hack to appease buggy tools, the only recourse is to set the sep argument of writeLines to the empty string, '', and insert the line breaks between lines manually (using paste).

Upvotes: 5

Related Questions