Home > Mobile >  Omitting the final end-of-line character for txt file (write.table in R)
Omitting the final end-of-line character for txt file (write.table in R)

Time:12-22

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

CodePudding user response:

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

CodePudding user response:

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

  • Related