Bioinformatician Bioinformatician - 4 months ago 21
R Question

R doesn't append lines to file (using Cat or Write)

I tried some options from stackoverflow(e.g.1) but this also doens't work so maybe there is a mistake in my code:

for (i in 1:length(lines)){
line = lines[i]
fields = strsplit(line, "\t")[[1]]
id = fields[1]
goIDs = fields[2:length(fields)]
list = as.list(GOCCANCESTOR[goIDs])
text = paste(toString(id), ":", toString(goIDs))
cat(text, file=fileConn, append=TRUE, sep = "\n")


when I run this code it keeps overwriting the data in the outputR.txt file.
Any suggestions to fix this problem?


the problem is that you are using a Fileconnection in combination with cat then the append won't work. There are several option you could use, the most easy one is to this:
first "create" the file, if you want to add a header for example:

header = "some header" 
## if you don't want to use a header then leave the header blank
header =""
cat(text, file="outputR.txt", append=FALSE, sep = "\n")

notice the append = FALSE this is necessary if you want to clear the file if it already exist otherwise you have to use append = TRUE
the you can write text to it using:

text = text = paste(toString(id), ":", toString(goIDs))
cat(text file="outputR.txt", append=TRUE, sep = "\n")