Search code examples
ralignment

aligning columns in a text file


Is there any way, using R, I can straighten up these first 3 columns and just to have one space between each. Currently, its more like a "tab".

Here is the content of the original file:

anim      sire      dam
4736    2A0584  2W151
4737    2A0584  2W151
4738    2A0584  2W151
4739    2A0584  2W151
4963    1W648   1W174
4964    1W648   1W174

I would like the contents of a new file to contain the original data, but to be like these columns with only a single space between each value

anim sire   dam
4736 2A0584 2W151
4737 2A0584 2W151
4738 2A0584 2W151
4739 2A0584 2W151
4963 1W648 1W174
4964 1W648 1W174

Solution

  • If that text is in a file as you present it here and you want a file with single spaces, then read it in:

     x <- read.table("f.txt", header = TRUE)
    

    Now write it out with the desired options (no row names, and no quotes):

     write.table(x, "outf.txt", sep = " ", row.names = FALSE, quote = FALSE)