# Get the available proj.db paths
library(tidyverse)
library(sf)
library(terra)
candidates <- c(system.file("share/proj", package = "sf"),
system.file("proj", package = "sf"),
system.file("share/proj", package = "terra"),
system.file("proj", package = "terra"))
candidates <- candidates[nzchar(candidates)]
candidates
file.exists(file.path(candidates, "proj.db"))GDAL/PROJ Error in R
Problem
When working with spatial data in R, I encountered the following error when using spatial analysis packages (e.g., sf, terra).
PROJ: proj_create_from_database: Cannot find proj.db (GDAL error 1)
This indicates that proj.db cannot be found when performing spatial processing tasks such as terra::project(). The proj.db file is a critical SQLite database that contains the definitions for coordinate reference systems (CRS) and the mathematical parameters required for transformations. It seems that people are encountering this kind of problem from time to time (e.g., [1], [2]).
The cause of this issue is likely a conflict between multiple GIS software installations (e.g., QGIS), which may overwrite global environment variables or installed R packages.
Solution
I solved this problem after uninstalling QGIS on my computer and reinstalling the terra package that was throwing the error. While looking for conflicting software might not always be this smooth, and uninstalling the software might not always be practical, another solution is to set the environment variable in the R session to point to a known valid proj.db file. For instance, if terra is experiencing issues but the sf package is working correctly, we can use the proj.db from sf.
# Set the PROJ_LIB environment variable to the valid proj.db path
Sys.setenv(PROJ_LIB = candidates[which(file.exists(file.path(candidates, "proj.db")))[1]])
Sys.getenv("PROJ_LIB")