onGiantShoulders
onGiantShoulders

Reputation: 95

Writing to a file inside an apply function

For memory reasons, I do not want to save the output of an apply function to a file, but I would like to write the results to a file while the apply loop is running.

I've made the following working example:

checkfun <- function(TheArray, fileConn){
    write(as.character(TheArray[1]), fileConn)
}
set.seed(1)
random_data <- matrix(nrow=10, ncol=10, data=runif(100))
outfile <- file("checkout.txt")
apply(random_data, 2, checkfun, fileConn=outfile)
close(outfile)

Reading the file checkout.txt will only contain the value (0.239629415096715) of the last column of the random_data matrix. Whereas I want it to save the full first row of that matrix in the checkout.txt file. Note that this is an example of the problem I'm facing, saving a row in a matrix is easy enough, I want to write to a file inside the apply function.

Is there something I'm doing wrong?

Just to be sure, the function in my original apply loop takes relatively long to finish, so I don't think writing to the file will produce too much overhead, even though it would produce quite some overhead in the function here.

Thanks.

Upvotes: 0

Views: 260

Answers (1)

danielson
danielson

Reputation: 1029

change 1 line of your code to open the file for writing in text mode:

outfile <- file("checkout.txt", "w")

Upvotes: 1

Related Questions