If I have this stack with three layers.
library(terra)
y <- rast(ncol=10, nrow=10, nlyr=3, vals=rep(1:3, each=100))
I would like to extract the values in one column as follows:
pixels 1 from lyr.1
pixels 1 from lyr.2
pixels 1 from lyr.3
pixels 2 from lyr.1
pixels 2 from lyr.2
pixels 2 from lyr.3
etc
CodePudding user response:
You can convert the SpatRaster to a data frame with the cell index and then manipulate it (e.g. with tidyverse
) to suit your needs:
library(terra)
#> terra 1.5.34
y <- rast(ncol=10, nrow=10, nlyr=3, vals=rep(1:3, each=100))
df <- as.data.frame(y, cells=TRUE)
# Tidyverse approach
library(tidyverse)
final_df <- df %>% pivot_longer(cols=c(lyr.1, lyr.2, lyr.3),
names_to = "layer") %>%
rename(pixel = cell)
final_df
#> # A tibble: 300 x 3
#> pixel layer value
#> <int> <chr> <int>
#> 1 1 lyr.1 1
#> 2 1 lyr.2 2
#> 3 1 lyr.3 3
#> 4 2 lyr.1 1
#> 5 2 lyr.2 2
#> 6 2 lyr.3 3
#> 7 3 lyr.1 1
#> 8 3 lyr.2 2
#> 9 3 lyr.3 3
#> 10 4 lyr.1 1
#> # ... with 290 more rows
Created on 2022-07-12 by the reprex package (v2.0.1)
CodePudding user response:
With
library(terra)
y <- rast(ncol=10, nrow=10, nlyr=3, vals=1:300)
You can get the values ordered as you want them like this
v <- values(y)
x <- as.vector( t(v) )
The trick is to use t
(transpose) before using as.vector
; otherwise the order of the values would be by layer (column in x
) instead of by cell.
You can turn vector x
into a matrix with
m <- matrix(x, ncol=1)
head(m)
# [,1]
#[1,] 1
#[2,] 101
#[3,] 201
#[4,] 2
#[5,] 102
#[6,] 202