R save multiple files with different names

吃可爱长大的小学妹 提交于 2020-01-23 17:05:06

问题


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


回答1:


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

mypath <- "/home//Desktop/percentage/"

for (i in 1:length(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 /.




回答2:


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)
}


来源:https://stackoverflow.com/questions/33520138/r-save-multiple-files-with-different-names

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!