rfor-loopwrite.table

Loop in output files?


I have a function that return the results in form of output files. The user write the desire name, as: test.dat and the function return the results in a file with this name in the local directory.

I want these files be numbered in increased order after run the for loop, by instance:

1.dat

2.dat

...

10000.dat

Basically, the idea is to put c("1.dat","2.dat",...,"10000.dat") in the vector output.


Solution

  • If we need a vector output and we are applying on a for loop, either initialize a NULL vector and concatenate the output from the function

    v1 <- c()
    for(i in 1:1e5) v1 <- c(v1, myfunction(arg1, arg2))
    v1 <- paste0(v1, ".dat")
    

    Or initialize 'v1' with the full length and assign based on the index

    v1 <- character(1e5)
    for(i in 1:1e5) v1[i] <- myfunction(arg1, arg2)
    v1 <- paste0(v1, ".dat")