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

如何将单个DataFrame按城市拆分并动态导出为多个CSV文件?

Dynamic CSV Export by City in R

Hey there! I notice you're currently writing repetitive code to export each city's data individually—let's fix that with a dynamic approach that works automatically for any number of cities in your dataset, no manual copy-pasting required.

Solution 1: Base R (No Extra Packages Needed)

We can use split() to break your data frame into a list of city-specific subsets, then loop through that list to export each subset as a CSV:

# Your original data setup (unchanged)
city=c("NYC","NYC","NYC","LONDON","LONDON","LONDON","PARIS","PARIS")
country=c("USA","USA","USA","UK","UK","UK","FRANCE","FRANCE")
year=c(2000,2000,2000,2010,2010,2010,2017,2017)
df=data.frame(city,country,year)

# Split the data frame into a list of city-specific subsets
city_subsets <- split(df, df$city)

# Loop through each subset to export as CSV
lapply(names(city_subsets), function(current_city) {
  # Create a filename using the city name
  output_file <- paste0(current_city, ".csv")
  # Export the subset to CSV (no row names included)
  write.csv(city_subsets[[current_city]], output_file, row.names = FALSE)
})

Solution 2: Tidyverse Approach (Using purrr)

If you're already using the tidyverse ecosystem, purrr::iwalk() makes this even cleaner by passing both the subset data and its corresponding city name directly:

library(purrr)

# Your original data setup (unchanged)
city=c("NYC","NYC","NYC","LONDON","LONDON","LONDON","PARIS","PARIS")
country=c("USA","USA","USA","UK","UK","UK","FRANCE","FRANCE")
year=c(2000,2000,2000,2010,2010,2010,2017,2017)
df=data.frame(city,country,year)

# Split and export in a single pipeline
split(df, df$city) %>%
  iwalk(function(city_data, city_name) {
    write.csv(city_data, paste0(city_name, ".csv"), row.names = FALSE)
  })

Why This Works Better

  • Scalability: Add new cities to your dataset later, and the code will automatically export their CSVs without any changes.
  • Less Repetition: No more copying/pasting the same code block for each city—reduces the chance of typos or errors.
  • Maintainability: Easier to update export settings (like adding na="" to handle missing values) in one place instead of multiple blocks.

内容的提问来源于stack exchange,提问作者san1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:54:10