如何使用st_read()批量导入多个GPX文件?
Hey there! Let's tackle your problem step by step. First, the character(0) result from list.files means R isn't finding any GPX files in the folder you specified—let's fix that first, then move on to reading all the files with sf and naming them properly.
1. Fix the list.files Empty Result
There are a few common reasons why this happens, let's check them one by one:
- Verify your folder path: Using
setwdcan be tricky, especially with spaces or special characters in folder names. Instead, usefile.path()to build your path safely (it handles OS-specific separators automatically):# Build the full path to your folder target_folder <- file.path("C:", "Documents", "feb 19 - Copy") # Check if the folder actually exists if (!file.exists(target_folder)) { stop("Whoops, that folder doesn't exist! Double-check the path.") } - Adjust your pattern matching: Windows is case-insensitive, but it's good practice to add
ignore.case = TRUEto catch files named.GPXtoo. Also, make sure your pattern matches the end of the filename with$:# List all GPX files (case-insensitive, no subfolders) myfiles <- list.files( path = target_folder, pattern = "\\.gpx$", full.names = TRUE, ignore.case = TRUE, recursive = FALSE # Set to TRUE if GPX files are in subfolders ) # Confirm we found files if (length(myfiles) == 0) { stop("No GPX files found! Check if the folder has .gpx files, or adjust the recursive flag.") }
2. Read All GPX Files with sf & Name Them
GPX files are layered (they contain waypoints, tracks, routes), so you need to specify which layer you want to read with st_read()—most likely you want the tracks layer. We'll use purrr::map() to read all files at once, then name each element in the list using the original filename.
First, load the required packages:
library(sf) library(purrr) library(tools) # For handling filenames
Then read and name the files:
# Read all GPX tracks into a list gpx_data <- map(myfiles, ~st_read(.x, layer = "tracks")) # Name each list element with the original filename (without path or .gpx suffix) names(gpx_data) <- file_path_sans_ext(basename(myfiles)) # Now you can access individual files by name! # Example: gpx_data$morning_run
Quick Notes
- If you need waypoints instead of tracks, just change
layer = "waypoints"inst_read(). - If you want to combine all tracks into a single sf object instead of a list, use
bind_rows(gpx_data)(but make sure all tracks have the same columns).
内容的提问来源于stack exchange,提问作者Betel

