Search code examples
rtextwrite.tablesink

R make lots of text files


Sample

x <- 1:10
fileConn<-file("file[x.txt")
writeLines("hello number",
           print(x), fileConn)
close(fileConn)

Here what I have is x which goes from 1 thru 10. I wish to make 10 files called "file1.txt" thru "file10.txt" that says

"hello number"
1

thru

"hello number"
10

for example.

edit- it should actually be

hello number 1

instead of

hello number
1

Solution

  • We could try using an apply function here:

    sapply(x, function(y) {
        name <- paste0("file", y, ".txt")
        fileConn <- file(name)
        writeLines(c("hello number", y), fileConn)
        close(fileConn)
    })
    

    If you don't want those default line breaks, then one option is to just call writeLines with a single character:

    writeLines(paste0("hello number ", y), fileConn)