Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to add layer name in the output of expanse function using terra package? #1446

Closed
bappa10085 opened this issue Mar 1, 2024 · 3 comments

Comments

@bappa10085
Copy link

bappa10085 commented Mar 1, 2024

I want to add the layer name in place of layer number in the output of expanse function using terra r package. Here is a reproducible example

library(terra)

# first create a raster
r1 <- r2 <- r3 <- rast(nrow=10, ncol=10)
# Assign random cell values
values(r1) <- runif(ncell(r1))
values(r2) <- runif(ncell(r2))
values(r3) <- runif(ncell(r3))
s <- c(r1, r2, r3)
names(s) <- c("a", "b", "c")
# classify the values into four groups
m <- c(0, 0.1, 1,
       0.1, 0.3, 2,
       0.3, 0.6, 3,
       0.6, 1, 4)

#Reclassify the raster stack
rclmat <- matrix(m, ncol=3, byrow=TRUE)
rc <- classify(s, rclmat, include.lowest=TRUE)

#Calculate frequency of pixels under each class
expanse(rc, unit="km", byValue = T)

As you can see from the output layer represents the layer number. Now how to add layer name in the output of expanse function using terra package?

@kadyb
Copy link
Contributor

kadyb commented Mar 1, 2024

I think this is not implemented yet, but for now you can just merge the layer number with its name.

df = expanse(rc, unit="km", byValue = T)
layer_names = data.frame(layer = seq_along(names(rc)), name = names(rc))
df = merge(df, layer_names, by = "layer")

@bappa10085
Copy link
Author

Thank you very much for such a quick reply. It will be great to have an argument like usenames = T in the freq function.

@rhijmans
Copy link
Member

with

e <- expanse(rc, unit="km", byValue = T)

You can do

e$name <- names(rc)[e$layer]

or

e$layer <- names(rc)[e$layer]

But I have now also added argument usenames as suggested such that you can do

expanse(rc, unit="km", byValue = T, usenames=T) |> head()
#  layer value      area
#1     a     1  47081113
#2     a     2  95712302
#3     a     3 163637536
#4     a     4 203634669
#5     b     1  82867639
#6     b     2  61724915 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants