简体   繁体   中英

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

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?

Notepad++ .txt 文件输出截图

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:

记事本加上“CR LF”和一个空行

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:

记事本加加一个“LF”并且没有后面的空行

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)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM