Creating txt file from a dataframe with specific fixed-width format

2.5k Views Asked by At

I have a data frame called dfGL with 22 columns and 17000 rows! The row names are: pressure, diameter, roughness...

I want to create a txt file from this data frame such that:

  • 1st column of dfGL starts from position 1 of the text file (Line 1 Column 1),
  • 2nd column starts at position 25 (Line 1 Column 25),
  • 3rd column starts at position 50 (Line 1 Column 50),
  • and so on! enter image description here
3

There are 3 best solutions below

0
On BEST ANSWER

Here is the solution that works:

library(gdata)

dfGL <- rbind(colnames(dfGL) , dfGL)
write.fwf(dfGL, file = "Inpuuuttt.txt", 
          width = 25,rownames = TRUE, colnames = FALSE,  quote = FALSE)
0
On

I would suggest using the write.fwf from the gdata package if you want to create a Fixed Width File. The col names don't seem to be saved to the correct position, so to work around this you can format them to the width you want the columns to be using formatC.

library(gdata)
colnames(dfGL) <- formatC(colnames(dfGL), width = 25, flag = " ")
write.fwf(dfGL, file = "C:/Users/sara/Desktop/Inputttt.txt", width = rep(25,ncol(dfGL)), sep="")
0
On

I think that what you are trying to do is to end up with a delimited text file with 24 blank columns between each adjacent variable. Here is a sort of roundabout and clunky solution. It will break if you have any strings with commas in any of your variables, has the annoying quality of having 24 commas written inside a string (you can count them with nchar()), and commits the offense of saving data to disk and then reading them back in.

# Export your data.frame to a csv file
write.csv(YourDataFrame, file="Path/To/File.csv", row.names=FALSE)

# Read in the lines of the file
fileLinesTemp = readLines("Path/To/File.csv")
# Add a bunch of commas to add columns
fileLinesTemp = gsub(",", ",,,,,,,,,,,,,,,,,,,,,,,,", fileLinesTemp)

# Write the new lines back to the file
fileConn = file("Path/To/File.csv")
writeLines(fileLinesTemp, fileConn)
close(fileConn)