2014-01-20 27 views
0

我有一個快速格式化問題。我有一組數據,在數據幀,看起來像這樣:格式化爲R中的文本文件

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

其中,用於編程輸入的目的,我需要改造成一個「.TXT」文件,這樣的格式:

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

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

顯然我的真實數據有數以萬計的條目,否則我可以手工完成。任何建議都會很棒。謝謝。

回答

1

這裏有一個辦法:

# 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") 

生成的文件:

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

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

列是製表符分隔。

+0

完美!非常感謝你。 –

0

該方法使用d_ply函數在處理之前分離動物。請注意,默認分隔符(空格)可以更改。

是否需要摺疊記錄?例如,如果dog對於steak有兩行,它們是否應以某種方式組合?如果是這樣,plyr方法應該能夠適應這一點,稍作修改即可。

ProcessAnimal <- function(d, fileLocation, delimiter=" ") { 
    cat(paste0("<", d$Animal[1], ">\n"), file=fileLocation, append=TRUE, sep="") 

    cat(sapply(seq_len(nrow(ds)), function(i) { 
    paste0(paste0(ds[i, c("Food", "FoodID")], collapse=delimiter), sep="\n") 
    }), file=fileLocation, append=TRUE, sep="") 

    cat(paste0("</", d$Animal[1], ">\n"), file=fileLocation, append=TRUE, sep="") 
} 

plyr::d_ply(.data=ds, .variables="Animal", .fun=ProcessAnimal, fileLocation="PetFood.txt") 

文本文件看起來像:

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