I recently started using R for spatial analysis and have some problems along the way.
I am using the elevatr package in R to make an elevation map for São Paulo state, Brazil. My idea is to use latitude, longitude and elevation values to extract climate variables from points on the map.
However I have a problem when trying to extract elevation values for points plotted on the map when using the st_crop
and aggregate
functions.
The code I'm using is following:
library(tidyverse)
library(sf)
library(elevatr)
library(stars)
library(rnaturalearthhires)
# São Paulo map:
brazil.est <- ne_states(country = 'Brazil', returnclass = 'sf')
sao_paulo.br <- brazil.est %>% filter(woe_name == "São Paulo")
# Random latitude and longitude points:
set.seed(123)
grid_points <- tibble(
x = runif(200, st_bbox(sao_paulo.br)[1], st_bbox(sao_paulo.br)[3]),
y = runif(200, st_bbox(sao_paulo.br)[2], st_bbox(sao_paulo.br)[4])
)
grid_points <- st_as_sf(grid_points, coords = c("x", "y"), crs=4326)
# Selectin points that are inside São Paulo map:
grid_points2 <- grid_points_teste %>%
mutate(on_land=lengths(st_within(grid_points_teste,sao_paulo.br))) %>%
filter(on_land==1)
ggplot()+
geom_sf(data=sao_paulo.br)+
geom_sf(data=grid_points, color="#000000")+
geom_sf(data=grid_points2, color="red")
# Elevation raster from elevatr package:
elevation_sp <- elevatr::get_elev_raster(locations = sao_paulo.br, z=8, clip =
"locations")
elevation.df <- as.data.frame(elevation_sp, xy=TRUE)
colnames(elevation.df)[3] <- "elevation"
elevation.df <- elevation.df[complete.cases(elevation.df),]
ggplot()+
geom_raster(data=elevation.df, aes(x=x, y=y, fill=elevation))+
geom_sf(data=sao_paulo.br, color="white", fill=NA)+
geom_sf(data=grid_points2, color="red")
# Extracting elevation values from points on the map using st_crop and aggregate:
grid_pontos.cortados2 <- st_crop(grid_points2, elevation_sp, crop=T, as_points =
all(na.rm = T))
sp_elevation_pontos <- aggregate(elevation_sp, grid_pontos.cortados2, mean)
And then it returns the following error even with the geometry column in the dataframe grid_pontos.cortados2
:
Error in Math.data.frame(list(on_land = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, :
non-numeric-alike variable(s) in data frame: geometry
Does anybody know the reason this error occurs or how to fix it? And have any tip to improve my code?