Marcin
Marcin

Reputation: 8044

Appending text in write function [R]

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

Answers (3)

rafa.pereira
rafa.pereira

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

Carl Witthoft
Carl Witthoft

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

Fabio
Fabio

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

Related Questions