4

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")
2
  • 1
    Look at ?paste for how to construct a string where i is evaluated to the current value between 1 and 300 instead of just taken as the letter "i". Commented Oct 20, 2013 at 18:59
  • 5
    something like paste("myarray", i, "csv", sep = ".") Commented Oct 20, 2013 at 19:00

3 Answers 3

12

There are multiple ways of going about this:

paste('myarray', i, 'csv', sep = '.')

or:

sprintf('myarray.%d.csv', i)

I prefer the last one.

Sign up to request clarification or add additional context in comments.

1 Comment

@PaulHiemestra, is sprintf preferred only because of the cleaner syntax or are there other reasons to it too?
1

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)

}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.