删除 R 中 write.table() 函数期间创建的附加行

问题描述 投票:0回答:1

将数据框写入 .txt 文件时,当您打开文本文件时,它会在文本文件中创建一个额外的行,但该额外的行在数据框中不可见,我已经尝试了很多选项来解决它。 示例 我已使用了所有推荐的建议,例如

trims()
writeLines()

但最后每当我将文件写入 .txt 时,它总是会创建一个附加行。有办法解决吗

我知道实际上我所要做的就是打开txt文件并删除最后一行。但我正在以这种方式写入 100 个文件,并且不可能对 100 个 txt 文件执行此操作。

附件是我使用过的代码:

library(readxl)
library(openxlsx)
library(dplyr)
library(tidyr)

# create a matrix of random numbers
data <- matrix(rnorm(5*3), nrow=5, ncol=3)

# create a vector of characters
chars <- letters[1:5]

# create a dataframe with random numbers and a character column
df <- data.frame(char_col=chars, data)

filename <- paste0("FileName_1,",".txt")
write.table(df, file = filename, row.names = FALSE, col.names = FALSE, quote = FALSE)

有人可以帮我吗,我已经尝试了一切,并且希望有一个解决方案。这还可行吗?

附件是写完本文后问题的快照。如下图黄线:

r dataframe dplyr
1个回答
0
投票

你可以编写 R 代码来丢弃最后一个字节,因为有一个换行符或一些你想要丢弃的字节

# open the connection to the file
in_filename <- "file.txt"
out_filename <- paste0("cleaned_",in_filename)
con_in <- file(in_filename, "rb")
con_out <- file(out_filename,"wb")
# get the total number of bytes in the file
size <- file.size(in_filename)

writeBin(readBin(con_in,
        what = "raw",
        n = size - 1 ),
        con = con_out )

# close the connection
close(con_in)
close(con_out)
 
© www.soinside.com 2019 - 2024. All rights reserved.