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

Feature request: Adding a by argument to rasterize #986

Closed
sambweber opened this issue Jan 26, 2023 · 1 comment
Closed

Feature request: Adding a by argument to rasterize #986

sambweber opened this issue Jan 26, 2023 · 1 comment

Comments

@sambweber
Copy link

Hi,

I was wondering whether it would be possible to incorporate a by = option into rasterize that allows you to rasterize vector data based on some factorial attribute and return a stack with one layer per factor level? It would be really useful in many situations e.g. rasterizing points by month or individual. At the moment I am doing it using a custom function:

rasterize_by(data, raster, by, ...){

rast(lapply(split(data, by), rasterize, y = raster, ...))

}

But the GIS students I teach aren't really aware of nesting and apply functions so it would be great to have it as a simple option in the CRAN version of the package. Apologies if there is already a way of doing this that I have missed!

Thanks,

Sam

@rhijmans
Copy link
Member

I have implemented that. Please give it a try. Here is an example for polygons.

library(terra)
f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)
r <- rast(v, ncols=75, nrows=100)
z <- rasterize(v, r, "NAME_2", by="NAME_1")

plot(z, fun=\()lines(v), plg=list(x="topright", cex=.7), mar=1.5, col=rainbow(6))

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

2 participants