I have a stack of rasters and I want to access each layer, combine each later with another file and finally export the resulting file as a csv file. Is there any way to do this with a loop? So far I have done this but I do not get a file for each raster layer:

for (i in 1:nlayers(sms))
  • 2
    Could you elaborate on a question more, like add comments to code? At what step does your script fails, what output do you actually get? I see that you are trying to extract values from layers and save them in separate tables. To my mind it will be more feasible to extract values from all the layers and just export the result column by column. – SS_Rebelious Oct 25 '13 at 19:40

First of all, I agree with @SS_Rebelious. Your "zipcoords" object seems to represent a common data extent so, rather than creating a list object, why not just create a stack object of your rasters and extract everything at once? If common extents are a problem in the rasters, you can use the "quick=TRUE" argument in stack() to override the extent error.

Seemingly, the problem with your code is that nlayers cannot be applied to a list object. However, based on this, there is something suspect in the description of your problem in relation to your code. If sms is, in fact, a list object then nlayers should be throwing an error before the loop even starts. Please check you object classes using class(). Are you sure that sms is not a raster stack or brick? Double brackets will work for indexing both object classes.

It would have been nice to see how sms was created. Based on your code it looks like it could be a list of character raster names and not raster objects. If your sms object is a list of raster names and not raster objects, you will need to create a raster object for each raster in the loop.

You do not need to create a new raster object to extract the values, it just adds unnecessary overhead. Additionally, since all you want is the named flatfile output, and have no other need for the raster name, you do not need assign.

for (i in 1:length(sms)) {
  y <- extract(sms[[i]], zipcoords)
  write.csv(y, file=paste0(getwd(),names(sms[[i]][1]),".csv"),row.names=F)

Have you tried using subset instead of your indexing-assign combination?

for (i in 1:nlayers(sms))
  sub <- subset(sms,i)
  y <- extract(sub,zipcoords) # Assuming zipcoords is overlaying your raster
  • sub <- raster[[x]] is actually a valid subseting method for raster bricks, so seems there is no need to use subset - the issue is not there. Though I don't like assign(x,raster(x)) too. But still waiting for clarifications from the topic starter. – SS_Rebelious Oct 26 '13 at 11:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.