rsavewrite.table

R save multiple files with different names


I have a variable named "data" which contains 10 lists, I want to save each list in different files (with different names). I know how to save an individual file but not how to write code for doing it through a loop. My biggest problem is with the name of the files.

I would like a folder with files with these names: percentage0.01.bed, percentage0.02.bed...)

I'm trying something like this:

percentages<-seq(0.01,0.1,0.01)
>percentages
 [1] 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.10
sapply(seq(length(data),function(x) write.table(data[x], sep= "    ", col.names=F, "/home//Desktop/percentage"+toString(cv[x]))

but it does not work...


Solution

  • I think you might do better with a for loop here. Try:

    mypath <- "/home//Desktop/percentage/"
    
    for (i in seq_along(percentages)) {
      write.table(percentages[i],
        file = paste0(mypath, paste("percentage", i, "bed", sep = ".")))
    }
    

    Note that I can't debug the part of this that specifies your desired path. I tried a version on my machine, and it worked fine. But be sure to include that last /.