aspire57
aspire57

Reputation: 1547

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...

Upvotes: 2

Views: 5221

Answers (2)

ulfelder
ulfelder

Reputation: 5335

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 /.

Upvotes: 4

vipul singhal
vipul singhal

Reputation: 61

saving multiple files with different names from data frame containing text.

for(i in 1:nrow(df)){
myfile<-paste0("file", "_", i, ".txt")
write.table(df[i,1],myfile,sep="\t",row.names=FALSE)
}

Upvotes: 0

Related Questions