Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 953
Marcin Kosiński Avatar asked Aug 16 '14 14:08

Marcin Kosiński


People also ask

How do I append to a text file in R?

Use append=TRUE to append lines to the existing text file.

Which function writes append data to a file in R?

In this article, we will see how to append rows to a CSV file using R Programming Language. By default, the write. csv() function overwrites entire file content. In order to append the data to a CSV File, use the write.

How do you add text to a file in python?

To write to a text file in Python, you follow these steps: First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.


2 Answers

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.

like image 174
Carl Witthoft Avatar answered Sep 29 '22 09:09

Carl Witthoft


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()
like image 35
rafa.pereira Avatar answered Sep 29 '22 09:09

rafa.pereira