I am trying to save different objects resulting from loop. I am using the funcion raster
to charge multiple images in different directories,the loop generetes these objects:
b : it generates the different directories where I have my images
[1] "C:/Users/franc/Documents/Fran/Tesis/Sin sincronizar/Imagenes Landsat/1985/Invierno/band3.tif"
[1] "C:/Users/franc/Documents/Fran/Tesis/Sin sincronizar/Imagenes Landsat/1986/Invierno/band3.tif"
[1] "C:/Users/franc/Documents/Fran/Tesis/Sin sincronizar/Imagenes Landsat/2004/Invierno/band3.tif"
name: the different names that I want to use to save the outputs
[1] "1985Banda3"
[1] "1986Banda3"
[1] "2004Banda3"
Then I want to use the directory b to charge the images, and save each one in each value of name
Here is my code:
library(raster)
a<-c(1985,1986,2004)
i<-1
while(i<=(length(a)))
{
b<-paste("C:/Users/franc/Documents/Fran/Tesis/Sin sincronizar/Imagenes Landsat/",a[[i]],
"/Invierno/band3.tif", sep = '')
name<-(paste(a[[i]],"Banda3", sep =''))
name<- raster(b)
i<-i+1
}
I want to generete this
1985Banda3 <- raster( "C:/Users/franc/Documents/Fran/Tesis/Sin sincronizar/Imagenes Landsat/1985/Invierno/band3.tif")
1986Banda3 <- raster( "C:/Users/franc/Documents/Fran/Tesis/Sin sincronizar/Imagenes Landsat/1986/Invierno/band3.tif")
2004Banda3 <- raster( "C:/Users/franc/Documents/Fran/Tesis/Sin sincronizar/Imagenes Landsat/2004/Invierno/band3.tif")
If you really want seperate variables, you can use
assign
, which gives you the full callassign(name, raster(b))
.However, I doubt whether it's really useful to have different variables for many objects that you want to handle the same way (I'm assuming your real data has more than 3 items). Because in a next step you want to do something with them, and you need those names again...
In my experience, working with a (named) list is a lot easier, which you can get this way:
Now you have a list, called Bandas, with 3 named elements.
To access e.g. the 2004 one, you can use
Bandas$Banda3_2004
, orname <- 'Bandar_2004'; Banda[['name']]
But not only do you have a cleaner workspace, it's also easier to do things to your objects:
And I've changed the names a bit, because from the documentation:
You can circumvent it (and
assign
complies with other names), but that means you have to use backticks (" ` ") around the name to refer to it.