While writing a data frame into a .txt file, it creates an additional row in the text file when you open it, but that extra row is not visible in the data frame and I have tried a lot of options to resolve it.
Examples I have used all the suggestions recommended like trims()
& writeLines()
.
But at the end whenever I write the file into .txt it always creates an additional row. Is there a way to resolve it.
I know in realistic terms all I have to do is open the txt file and delete the last row. But I am writing 100 of files in such a manner and it is not possible to do this for 100 txt files.
Attached is the code which I have used:
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)
Can someone help me out, I have tried everything and would love a solution for this. Is this even doable?
Attached is the snapshot of the issue after writing this. The yellow line shown below:
You can write R code to throw away the last byte given that theres a LineFeed or some such there that you want to throw away
# 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)
#Writing the output to local drive
writeBin(readBin(con_in,
what = "raw",
n = size - 2 ),
con = con_out )
# close the connection
close(con_in)
close(con_out)