2 years ago
#76532
user197410
Why am I losing headers when coverting txt to csv in R?
I am trying to convert multiple txt files to csv files in R using the following code:
directory <- "/My directory"
ndirectory <- "/My directory"`
file_name <- list.files(directory, pattern = ".txt")
files.to.read <- paste(directory, file_name, sep="/")
files.to.write <- paste(ndirectory, paste0(sub(".txt","", file_name),".csv"), sep="/")
for (i in 1:length(files.to.read)) {
temp <- (read.csv(files.to.read[i], header = TRUE, skip = 11, fill = TRUE))
write.csv(temp, file = files.to.write[i])
}
The files convert fine but my column headings change,instead of the given headings I get headings like "X11, X122.5 etc). I have tried specifying header=TRUE in various places, but get errors no matter where I put it. I am very new to R and coding and I have now spent 2.5 hours on this problem and I am sure the solution is obvious. Can anyone assist?
Below I have pasted a small sample of the txt files I am converting:
"Run_Number","Score","Cost","Planning_Units","Connectivity","Connectivity_Total","Connectivity_In","Connectivity_Edge","Connectivity_Out","Connectivity_In_Fraction","Penalty","Shortfall","Missing_Values","MPM"
1,1220162.943419,1597.280000,565,42463.330000,1743907.359000,498873.894000,42463.330000,1202570.135000,0.286067,1216442.496919,401.220200,17,0.000000
2,1221940.723569,1591.690000,502,78130.733000,1743907.359000,394927.265000,78130.733000,1270849.361000,0.226461,1216442.496919,401.220200,17,0.000000
3,1221587.652669,1578.640000,564,71330.315000,1743907.359000,473868.424000,71330.315000,1198708.620000,0.271728,1216442.496919,401.220200,17,0.000000
4,1221351.923169,1585.450000,462,66479.525000,1743907.359000,365484.303000,66479.525000,1311943.531000,0.209578,1216442.496919,401.220200,17,0.000000
5,1220767.805969,1450.620000,518,57493.781000,1743907.359000,457270.801000,57493.781000,1229142.777000,0.262210,1216442.496919,401.220200,17,0.000000
6,1221883.615269,1661.300000,532,75596.367000,1743907.359000,420648.224000,75596.367000,1247662.768000,0.241210,1216442.496919,401.220200,17,0.000000
7,1220654.911119,1867.380000,652,46900.684000,1743907.359000,619166.210000,46900.684000,1077840.465000,0.355045,1216442.496919,401.220200,17,0.000000
r
data-conversion
0 Answers
Your Answer