When using as.data.frame to handle multiple layers, for the merged layer all the naming is lyr.1
. Is there a better way to solve this naming problem?
library(terra)
m <- matrix(1:25, nrow=5, ncol=5)
rm <- rast(m)
n <- matrix(rep(5,time=25),nrow = 5,ncol = 5)
rn <- rast(n)
dt <- c(rm,rn)
data <- terra::as.data.frame(dt,xy=TRUE)
head(data)
> head(data)
x y lyr.1 lyr.1
1 0.5 4.5 1 5
2 1.5 4.5 6 5
3 2.5 4.5 11 5
4 3.5 4.5 16 5
5 4.5 4.5 21 5
6 0.5 3.5 2 5
Is it possible to bring the original names into the layers (in the example: rm
and rn
)?
You can set the layer names with names<-
Your data
library(terra)
rm <- matrix(1:25, nrow=5, ncol=5) |> rast()
rn <- matrix(rep(5,time=25),nrow = 5,ncol = 5) |> rast()
dt <- c(rm, rn)
set the names
names(dt) <- c("A", "B")
terra::as.data.frame(dt,xy=TRUE) |> head(2)
# x y A B
#1 0.5 4.5 1 5
#2 1.5 4.5 6 5
You could also do
dt <- terra::rast(c(A=rm, B=rn))
terra::as.data.frame(dt,xy=TRUE) |> head(2)
# x y A B
#1 0.5 4.5 1 5
#2 1.5 4.5 6 5