I am trying to grab mean NDVI values in the parcels by using terra::extract(). I noticed that my dataframe from terra::extract() gives me NA values (in fact I have 2494 NA values out of 4519 observations). My NDVI raster has a spatial resolution of ~0.5 feet (0.15 meters). Below is my code. I have also tried out exactextractr::exact_extract() but it didn't give me the same values as raster::extract(). From what I've read, exactextractr::exact_extract() accounts for the portion of the cell lying inside the polygon. I'm wondering what is better to use, exactextractr::exact_extract() or terra::extract(). Any help/guidance would be great!
epa_fatparcels_sidewalk_adjacent <-
epa_parcels_sidewalk_adjacent %>%
st_transform(projection) %>%
st_buffer(330) %>%
st_transform(st_crs(epa_ndvi))
tictoc::tic()
epa_ndvi_sr<- terra::rast(epa_ndvi)
epa_fatparcels_sidewalk_adjacent_sv <- epa_yards_sidewalk_adjacent %>%
st_transform(st_crs(epa_ndvi)) %>%
#--- convert to a SpatVector object ---#
as(., "Spatial") %>% terra::vect()
epa_fatparcels_ndvi_v2 <- terra::extract(
epa_ndvi_sr,
epa_fatparcels_sidewalk_adjacent_sv,
fun="mean"
)
tictoc::toc() #took 17.92 sec elapsed
Please provide a self-contained minimal reproducible example when asking a R question.
You can add na.rm=TRUE
to ignore the NA
values
epa_fatparcels_ndvi_v2 <- terra::extract(
epa_ndvi_sr,
epa_fatparcels_sidewalk_adjacent_sv,
fun="mean", na.rm=TRUE
)
Also, this line
as(., "Spatial") %>% terra::vect()
Can probably be simplified to
terra::vect()
As for exactrextactr
--- that matters most if the cells are relatively few. With terra::extract
you can use argument exact=TRUE
to get the same result.
@MireilleVargas This may have to do with which column within the raster terra::extract()
is using. The same thing was happening to me so I investigated further by cross referencing in ArcMap and figured out it was pulling the "Count" column--which counts how many pixels there are of each specific value--rather than the "Value" column. I noticed this occurs both when importing said raster via rast
and when converting a RasterLayer to a SpatRast object. It seems the raster package perhaps automatically detects the value columm, but in terra, to switch the active category being extracted from a raster use the activeCat()
function. For example, activeCat(ndviRast) <- 2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.