Reputation: 8044
I am trying to append a line in an already existing .txt
file. But my syntax overwrites this file :(
fileConn <- file( "realization1.txt" )
write(x =as.character(max(cumsum( rnorm( 10^7)))),
file = fileConn,
append = TRUE, sep = " ")
write(x =as.character(max(cumsum( rnorm( 10^7)))),
file = fileConn,
append = TRUE, sep = " ")
}
close( fileConn )
Does anybody have any solution to this? Thanks for help!
Upvotes: 6
Views: 925
Reputation: 13807
You can also use writeLines
, which is about 20x faster than write
. This makes a big difference if you are appending large character strings.
sink("outfile.txt", append = T)
x <- as.character(max(cumsum( rnorm( 10^7))))
writeLines(x)
sink()
Upvotes: 2
Reputation: 21502
I believe your difficulty comes from failing to open the file with the proper attributes set.
If you create the connection with fileConn <- file( "realization1.txt" ,open="a")
, then all will work as you expect. Basically, so far as I can tell, write
(which is a wrapper for cat
) cannot append unless the file connection was opened with "append" allowed.
Upvotes: 5
Reputation: 518
I would just use the command write.table
write.table(max(cumsum( rnorm( 10^7))),file="realization1.txt",append=TRUE,row.names=FALSE,col.names=FALSE)
write.table(max(cumsum( rnorm( 10^7))),file="realization1.txt",append=TRUE,row.names=FALSE,col.names=FALSE)
You will find the 2 values in the 'realizaion1.txt' file
Upvotes: 0