You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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 setwd can be tricky, especially with spaces or special characters in folder names. Instead, use file.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 = TRUE to catch files named .GPX too. 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" in st_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 09:27:43