user2524854
user2524854

Reputation: 23

Argument used for stack function (raster library) for R

I am trying to create a RasterStack object with the stack function from the Raster library in R,

library(raster)

but I am having issues with the arguments used in the function. Let me show what I am doing:

###set working directory
setwd("myworkingdirectory")

###Upload variables
v1 <- raster("variable1.tif")
v2 <- raster("variable2.tif")
v3 <- raster("variable3.tif")
v4 <- raster("variable4.tif")

So, if I type :

###Creating RasterStack object
var.stacked <- stack(v1, v2, v3)

The function works properly and stacks the three variables.

However, I have to do this process for different runs that differ in the numbers of variables required, so I created a loop that outputs a character variable with the correct number and types of variables for each run. For example:

###Output from loop
print(num.vars)
[1] "v1" "v3" "v4"         

I tried to write something like the following code, in hopes of getting the process working, but it is not:

var.stacked <- stack(num.vars)

Error in .local(.Object, ...) : 
  `myworkingdirectory\e1' does not exist in the file system,
and is not recognised as a supported dataset name.


Error in .rasterObjectFromFile(x, band = band, objecttype = "RasterLayer",  : 
  Cannot create a RasterLayer object from this file. (file does not exist)

Why is R trying to find the variable names (v1, v2, v3, v4 in this case) in the working directory that I set up in the beggining of the code but not in the default .GlobalEnv like it does when I explicitly write stack(v1, v2...) ?

Any help to make the code work would be very appreciated. Also I am not very experienced with R and this is the first time I post a question here, so if my question needs more clarification please let me know as well.

Thank you in advance!

Upvotes: 2

Views: 827

Answers (1)

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59970

Because you are passing a character vector to stack which then interprets it as a filename in the current working directory. Instead you could do this if you have already created your raster objects in R...

stack( mget( num.vars , env = .GlobalEnv ) )

mget takes the character vector of raster object names and returns a list of raster objects.

stack then stack the rasters in the list into a stack.

Upvotes: 3

Related Questions