Get Nearest Climate Value by Coordinates

日本語版はこちら (Japanese version)

This chapter introduces get_nearest_climate_value(), which returns climate variable values from the nearest mesh cell to given coordinates. The function source file is R/get_nearest_climate_value.R.

Load library

Load data

data_dir <- Sys.getenv("PROJECT_DATA_DIR")
sf_climate <- readRDS(file.path(
  data_dir,
  "climate_mesh_data_joined/climate_mesh_data_with_aridity_index.rds"
))

Define the function

source("../R/get_nearest_climate_value.R")

Usage

Get nearest aridity_index for one coordinate

result <- get_nearest_climate_value(
  sf_climate,
  lon = 139.6917,
  lat = 35.6895,
  value_col = "aridity_index"
)
print(result)

Get multiple variables for one coordinate

result <- get_nearest_climate_value(
  sf_climate,
  lon = 139.6917,
  lat = 35.6895,
  value_col = c("aridity_index", "precipitation_year")
)
print(result)

Get nearest values for a data frame of coordinates

df_input <- data.frame(
  id = 1:3,
  longitude = c(139.6917, 135.5022, 130.4181),
  latitude = c(35.6895, 34.6937, 33.5902)
)
result <- get_nearest_climate_value(
  sf_climate,
  df = df_input,
  lon_col = "longitude",
  lat_col = "latitude",
  value_col = c("aridity_index", "precipitation_year")
)
print(result)

Get all attributes

result <- get_nearest_climate_value(
  sf_climate,
  lon = 139.6917,
  lat = 35.6895,
  value_col = NULL
)
print(head(result))