Reputation: 311
I have an array. It has lat,lon,time,and value. Time starts from 1 to 300. Here is part of array for time=1.
myarray[,,1]
lon
lat -124.5 -123.5 -122.5 -121.5 -120.5 -119.5 -118.5
31.5 0 0 0 0 0 0
32.5 0 0 0 0 0 0
33.5 0 0 0 0 0 0
34.5 0 0 0 0 0 0
35.5 0 0 0 0 0 0
36.5 0 0 0 768.1 0 126.2
37.5 0 0 0.2 0 811 212.1
38.5 0 0 3055 0 243.9 243.7
39.5 0 0 1.5 0.1 3 0
40.5 0.1 16.8 4.3 0.5 2.1 0
41.5 0.2 398.6 0.4 1.2 1.6 0
42.5 0 0.1 0.9 0.1 0.7 0
I want to use "write.csv" and "for loop" at the same time to read the data from array for each time step (1 to 300) and store them in individual .csv files which has "i" as index. I used this command but it seems that it doesn't work:
for (i in 1:300) write.csv(myarray[,,i],"myarray.i.csv")
Upvotes: 4
Views: 26361
Reputation: 33137
This should work fine:
n = dim(mydata)[3]
for(i in 1:n) {
#unpack a 3D array
mat = mydata[,,i]
form = sprintf('subject_%s.csv', i)
write.csv(mat, file = form)
}
Upvotes: 1
Reputation: 2077
One way is
for (i in 1:300) {
write.table(myarray[,,i],file=""myarray.i.csv"",append=TRUE,sep=",",col.names=TRUE,row.names=TRUE)
}
Upvotes: 0
Reputation: 60924
There are multiple ways of going about this:
paste('myarray', i, 'csv', sep = '.')
or:
sprintf('myarray.%d.csv', i)
I prefer the last one.
Upvotes: 12