Search code examples
rfixed-width

R: Fixed widths aligned left


I am trying to save a data.frame to a file in this way:

library(gdata)
write.fwf(mydata,file = "myfile.txt",width = c(12, 7), eol="\r\n", colnames = FALSE, justify = "left")

the data are very plain:

V1 V2
1   foo
2   bar
3   ter
4   four

However the generated output put the values aligned to right instead of left:

           1    foo
           2    bar
etc

instead of

1            foo
2            bar
etc

so it pads from the left with spaces instead from the right.

How can I fix it?


Solution

  • As the help page of write.fwf and format indicate: the justify argument only applies to character columns. It doesn't seem possible to left align number using format.

    One way to do this would be to first cast the numeric column to a character column manually using, for example, sprintf:

    mydata$V1 <- sprintf("%-12d", mydata$V1)
    

    The %d indicates that you want to format an integer, the 12 is the width of the field and the - indicates left alignment.

    I must say, that this is what I usually do when writing fixed width files: first convert all column to character with the correct widths etc, and then do:

    lines <- do.call(paste0, mydata)
    writeLines(lines, "myfile.txt")