Reputation: 189
I have many matrices with similar names. These matrices are the results of simulations that take hours to run. I want to be able to preserve these simulated results, so I can go about conducting an analysis. I do NOT want to have to run the simulations everyday in order to generate the results again, to continue my analysis. Therefore, I have decided to export each matrix as a csv. But, I am hoping there is an easy way to export ALL of my matrices as individual csv's instead of typing this code over and over
write.csv(mymatrix1, file="mymatrix1")
The matrix names might be revelant for a possible solution. Every matrix starts with "sample." After the period is a unique number.
I was thinking of some sort of loop, or possibly the use of a Wild Card? I don't know... Thanks!
Upvotes: 1
Views: 88
Reputation: 388
If you have your file names, you can put them in a vector, and then call sapply in order to recursively call write.csv.
names <- c(a, b, c)
sapply(names, function(x) write.csv(x, file=as.character(x)))
Upvotes: 1
Reputation: 1210
If the matrices are all in R:
for(i in ls(pattern="sample.")) {
write.csv(i, file=paste(i,".csv",sep=""))
}
Upvotes: 1
Reputation: 70653
You can construct the name using sprintf
function. Then it's just a matter of fetching the object.
my.obj <- sprintf("sample%s", i) # i would be a variable you can control
write.csv(get(my.obj), file = paste(my.obj, ".csv", sep = ""))
Upvotes: 1
Reputation: 819
as you said, you can do a loop the task that you want. Here is a small exmaple:
sample.1<-matrix(0,ncol=10,nrow=10)
sample.2<-matrix(0,ncol=10,nrow=10)
sample.3<-matrix(0,ncol=10,nrow=10)
for( i in 1:3){
matname<-paste0("sample.",i)
write.csv(get(matname),file=paste0(matname,".csv"))
}
Upvotes: 1
Reputation: 4385
Just use get
and a for
loop to save them
for (i in 1:num_samples)
write.csv(get(paste0('sample.',i)),file=paste0('mymatrix',i))
Upvotes: 0