dbo
dbo

Reputation: 1234

exporting and formatting data.frame as .dat table

I'm looking for help creating an input file (eg df.dat) from a data.frame for a legacy program that has very strict formatting requirements. With this example data.frame:

location <- rep("GDWC1",6)
monyear <- rep(0215, 6)
day <- c(6,7,8,9,10,11)
value <- c(750.00, 3516.00, 8295.00, 11064.00, 3264.00, 111796.00)
df <- data.frame(location, monyear, day, value)
head(df)
# location monyear day  value
#1    GDWC1    0215   6    750
#2    GDWC1    0215   7   3516
#3    GDWC1    0215   8   8295
#4    GDWC1    0215   9  11064
#5    GDWC1    0215  10   3264
#6    GDWC1    0215  11 111796

My desired file export (eg say as a .dat, .txt) format is no header or row IDs, 6 spaces between the first and second column (which is always four values - here the 0215), right justified 3rd column (2-3 spaces between 2nd & 3rd column), and at least 2 spaces between 3rd and 4th column, and adding .00 to the 4th column with decimal alignment enforced.

desired df.dat:

GDWC1      0215   6     750.00
GDWC1      0215   7    3516.00
GDWC1      0215   8    8295.00
GDWC1      0215   9   11064.00
GDWC1      0215  10    3264.00
GDWC1      0215  11  111796.00

I've been unsuccessful with write.table(), in getting the columns spacings, right justfication of the day column, and decimal alignment for the value column all correct. Any ideas? Thank you!

Upvotes: 0

Views: 224

Answers (1)

Ian Campbell
Ian Campbell

Reputation: 24810

Here's an approach with sprintf:

result <- apply(df,1,function(x){
  paste0(x["location"],
         sprintf("%6s",""),
         sprintf("%04s",x["monyear"]),
         sprintf("%4s",x["day"]),
         sprintf("%11.2f",as.numeric(x["value"]))
         )})
write.table(result,
            file = "file.dat",
            col.names = FALSE,
            row.names = FALSE,
            quote = FALSE)

system("cat file.dat")
GDWC1      0215   6     750.00
GDWC1      0215   7    3516.00
GDWC1      0215   8    8295.00
GDWC1      0215   9   11064.00
GDWC1      0215  10    3264.00
GDWC1      0215  11  111796.00

See help(sprintf) for details on how the format works.

Upvotes: 1

Related Questions