Search code examples
rfixed-widthmultiple-columns

Setting column width in a data set


I would like to set column widths (for all the 3 columns) in this data set, as: anim=1-10; sireid=11-20; damid=21-30. Some columns have missing values.

anim=c("1A038","1C467","2F179","38138","030081")
sireid=c("NA","NA","1W960","1W960","64404")
damid=c("NA","NA","1P119","1P119","63666")

mydf=data.frame(anim,sireid,damid)

Solution

  • From reading your question as well as your comments to previous answers, it seems to me that you are trying to create a fixed width file with your data. If this is the case, you can use the function write.fwf in package gdata:

    Load the package and create a temporary output file:

    library(gdata)
    ff <- tempfile()
    

    Write your data in fixed width format to the temporary file:

    write.fwf(mydf, file=ff, width=c(10,10,10), colnames=FALSE)
    

    Read the file with scan and print the results (to demonstrate fixed width output):

    zz <- scan(ff, what="character", sep="\n")
    cat(zz, sep="\n")
    
    1A038      NA         NA        
    1C467      NA         NA        
    2F179      1W960      1P119     
    38138      1W960      1P119     
    030081     64404      63666    
    

    Delete the temporary file:

    unlink(ff)