I've read in several .asc files as rasterlayer with tk_choose.files and they are now in a list xz.list
:
library(tcltk)
library(raster)
xz.list <- lapply(tk_choose.files(caption = "Choose Layers"), raster)
As the number of components in the list depends on how many .asc files are read in, I'm looking for a way to unlist xz.list
that every component is written as a variable x.1
to x.i
automatically. I tried this with no luck:
for( i in 1:length(xz.list) ){
assign( paste("x" , i , sep = "." , xz.list[[i]]))
}
UPADATE:
Sorry for my unclear example. I try to be more precise:
Create a raster list:
xz.list <- lapply(1:5,function(x){
r1 <- raster(ncol=3, nrow=3)
values(r1) <- 1:ncell(r1)
r1
})
Now I would like to split the list in every single layer like this:
x.1 <- xz.list[[1]]
x.2 <- xz.list[[2]]
x.i <- xz.list[[i]]
The output should look like this for every layer from xz.list
:
x.1
class : RasterLayer
dimensions : 3, 3, 9 (nrow, ncol, ncell)
resolution : 120, 60 (x, y)
extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
data source : in memory
names : layer
values : 1, 9 (min, max)
The problem is, that the number of layers in xz.list
are varying with the number of layers chosen with tk_choose.files
. So I need to find a way to split xz.list
in every of its layers and put every single layer in a variable from x.1
to x.i
without knowing the number of layers before. i
stands for the number of layers in xz.list
.
It is not clear the expected output since you don't show it in a reproducible example. But Here 3 possibilities.
lapply(xz.list,as.matrix)
lapply(xz.list,getValues)
getValues(stack(xz.list)) ## personally I prefer this one
For example , I crate the rastes list as:
xz.list <- lapply(1:5,function(x){
r1 <- raster(ncol=3, nrow=3)
values(r1) <- 1:ncell(r1)
r1
})
Then , stack method
getValues(stack(xz.list))
layer.1 layer.2 layer.3 layer.4 layer.5
[1,] 1 1 1 1 1
[2,] 2 2 2 2 2
[3,] 3 3 3 3 3
[4,] 4 4 4 4 4
[5,] 5 5 5 5 5
[6,] 6 6 6 6 6
[7,] 7 7 7 7 7
[8,] 8 8 8 8 8
[9,] 9 9 9 9 9
as.matrix method
lapply(xz.list,as.matrix)
[[1]]
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
[[2]]
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
......
getValues method
lapply(xz.list,getValues)
[[1]]
[1] 1 2 3 4 5 6 7 8 9
[[2]]
[1] 1 2 3 4 5 6 7 8 9
[[3]]
[1] 1 2 3 4 5 6 7 8 9
......