2

I have a simple data.frame that I would like to write to an output .txt file using R.

Sample code:

my_df <- data.frame(name = c("Wendy", "Quinn"), age = c(23, 43))
write.table(my_df, file = "my_output_file.txt", sep = " ", col.names = F, row.names = F, quote = F, eol = "\n")

The trouble is that I am getting the following output file when viewed in Notepad++ (see screenshot). I understand the eol = "\n" argument places a carriage return at the end of each line -- I want that for the line separation between these two rows, but not at the end of the document. Is there a method to omit the final carriage return that results in my .txt file being 3 lines long instead of only 2?

Screenshot of Notepad++ .txt file output

Peter
  • 11,500
  • 5
  • 21
  • 31

2 Answers2

1

I don't know of an automatic way to do it, but try this:

my_df <- data.frame(name = c("Wendy", "Quinn"), age = c(23, 43))
write.table(my_df, file = "my_output_file.txt", sep = " ", col.names = F, row.names = F, quote = F, eol = "\n")

produces the same output:

notepad plus plus with "CR LF" and an empty line

but this

my_output <- capture.output(write.table(my_df, sep = " ", col.names = F, row.names = F, quote = F, eol = "\n"))
writeBin(paste(my_output, collapse = "\n"), "my_output_file2.txt")

produces this:

notepad plus plus with one "LF" and no following empty line

r2evans
  • 141,215
  • 6
  • 77
  • 149
1

You can write the object minus the last line, then append it without a line ending.

write.table(my_df[1:(nrow(my_df)-1),], file = "my_output_file.txt", 
  sep = " ", col.names = F, row.names = F, quote = F, eol = "\n")
write.table(my_df[nrow(my_df),], file = "my_output_file.txt", 
  sep = " ", col.names = F, row.names = F, quote = F, eol = "", append=T)

enter image description here

Andre Wildberg
  • 12,344
  • 3
  • 12
  • 29