Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)
edited by

I want to assign values to a number of raster files in a folder, and apply the raster() function to them, with the eventual aim to plot, stack, and subject algebra to them. So each raster file in the folder would be assigned to "r1", "r2" etc. So far I have executed the following:

f <- list.files(path="path/to/files", pattern="*.tif", full.names=TRUE, recursive=FALSE)

r <- lapply(f, raster)

lapply(r, function(i){

  assign(paste0("r", i), i)

})

However, if I return r1, it only gives the following output:

> r1

[1] 1

1 Answer

0 votes
by (108k points)

I think it is better not to use the assign in R programming. It is a typical beginner's mistake to think you need it. There are very few good uses of it and you will likely never need it. Using it leads to horrible code with many objects that you have called by name.

If you want to use names, you could give names to the elements of the list.

names(r) <- paste0("r", 1:length(r))

Or the layers have the same extent and resolution, make a RasterStack and name the layers:

s <- stack(r)

names(s) <- paste0("r", 1:nlayers(s))

Browse Categories

...