0

I have several ncdf files in a folder. I would like to stack them individually in a loop and print their information in R.

I have the following code:

library(raster)
library(ncdf4)

c <- list.files(pattern="nc")
for (i in 1:length(c)){
   ff <- stack(c[i])
   print(ff[i])
}

by typing ff[1] in the command line, I expected to get that:

class       : RasterStack 
dimensions  : 444, 922, 409368, 10  (nrow, ncol, ncell, nlayers)
resolution  : 0.0625, 0.0625  (x, y)
extent      : 235.375, 293, 25.125, 52.875  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
names       : X1, X2, X3, X4, X5, X6, X7, X8, X9, X10 

but I get the following:

X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
[1,] NA NA NA NA NA NA NA NA NA  NA
X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
[1,] NA NA NA NA NA NA NA NA NA  NA

I do not see where is my error. Thanks for any help.

Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
armin
  • 77
  • 8

1 Answers1

1

Instead of print(ff[i]), you want to do print(ff).

ff is a RaxterStack. ff[i] will give you the values of cell i.

((If you wanted layer j, you can do ff[[j]]))

Avoid c as a variable name (it is also a function). I would do

library(raster)
ff <- list.files(pattern="nc")
for (i in 1:length(ff)) {
   s <- stack(ff[i])
   print(s)
}

or better

for (i in 1:length(ff)) {
   b <- brick(ff[i])
   print(b)
}

or perhaps like this:

library(raster)
ff <- list.files(pattern="nc")
lapply(ff, brick)
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
  • What I would like is to get access to rasterStack 1, and rasterStack2. I am not looking for accessing the raster layer. – armin Feb 26 '19 at 03:14
  • Yes: use `print(ff)` – Robert Hijmans Feb 26 '19 at 04:11
  • with these lines of code: for (i in 1:length(ff)) { s <- stack(ff[i]) print(s) } It print all the rasterStack but I do not understand how I can retrieve each individual stack after. For example, I would like to access the rasterStack n*50 in the iteration of the loop. – armin Feb 26 '19 at 04:39
  • I do not understand what you are saying. Perhaps you can edit your question to explain what you want. – Robert Hijmans Feb 26 '19 at 05:57