Search code examples
rtextdataformat

Formatting into text file in R


I have a quick formatting question. I have a set of data in a data frame that looks like this:

Animal   Food   Food ID
 dog     steak   100
 dog     beef    200
 dog     poo     001
 cat     milk    020
 cat     steak   100
 cat     beef    200

which, for programming input purposes, I need to transform into a '.txt' file with a format like this :

<dog>
steak   100
beef    200
poo     001
</dog>

<cat>     
milk    020
steak   100
beef    200
</cat>

Obviously my real data has tens of thousands of entries or else I could do it by hand. Any suggestions would be great. Thanks.


Solution

  • Here's a way:

    # create the string
    text <- paste0(sapply(unique(dat$Animal), function(x) {
      subdat <- dat[dat$Animal == x, -1]
      subdat[[2]] <- sprintf("%03d", subdat[[2]])
      paste0("<", x, ">\n",
             paste(capture.output(write.table(subdat, sep = "\t",
                                              quote = FALSE, row.names = FALSE, 
                                              col.names = FALSE)), collapse = "\n"),
             "\n</", x, ">")
    }), collapse = "\n\n")
    
    # write it to a file
    write(text, file = "filename.txt")
    

    The resulting file:

    <dog>
    steak   100
    beef    200
    poo 001
    </dog>
    
    <cat>
    milk    020
    steak   100
    beef    200
    </cat>
    

    The columns are tab-delimited.