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

如何编写R循环批量子集数据合并空间地图生成动态GIF

你可以直接用年份序列遍历实现全流程循环,不需要为每一年单独创建独立数据对象,同时把仅需运行一次的预处理逻辑提前到循环外,执行效率更高,完整实现代码如下:

# 加载需用到的包(如果已加载可跳过)
library(classInt)
library(colorspace)
# 提前处理kommune字段,仅需运行1次,不需要重复放到循环里
kommune$KOMNAVN <- gsub(" Kommune", "", kommune$KOMNAVN)
# 定义需要处理的年份范围
years <- 2007:2019
# 遍历所有年份执行处理
for (y in years) {
  # 1. 提取当年数据子集
  summerhouses_year <- summerhouseprices[, c("Kommune", as.character(y))]
  
  # 可选:打印结构检查,不需要可以注释掉
  cat("===== 正在处理", y, "年数据 =====\n")
  print(dim(summerhouses_year))
  str(summerhouses_year$Kommune)
  str(summerhouses_year[[as.character(y)]])
  
  # 2. 合并空间数据
  Municipality_year <- merge(kommune, summerhouses_year, 
                            by.x = "KOMNAVN", by.y = "Kommune", all = FALSE)
  # 可选:打印表头检查
  print(head(Municipality_year[[as.character(y)]]))
  
  # 3. 生成价格区间与配色
  p_intervals <- classIntervals(Municipality_year[[as.character(y)]], 5, 
                                style = "fixed", fixedBreaks = c(0,1,10000,20000,30000,40000))
  p_Colours <- findColours(p_intervals, sequential_hcl(5, palette = "Reds2"))
  
  # 4. 绘制地图并保存png
  png(filename = paste0(y, ".png"), width = 800, height = 600) # 可以自行调整尺寸
  plot(sea, col = "cadetblue3")
  plot(kommune, col = "beige", add = TRUE)
  plot(Municipality_year, axes = TRUE, col = p_Colours, add = TRUE)
  # 添加图例
  legend("topright", 
         fill = attr(p_Colours, "palette"), 
         border = "black", 
         legend = gsub(",", " - ", names(attr(p_Colours, "table"))), 
         bg = "white",
         title = paste0("Summerhouse prices ", y))
  dev.off()
}
# 可选:生成动态GIF,需要先安装gifski包
# install.packages("gifski")
library(gifski)
png_files <- paste0(years, ".png")
gifski(png_files, gif_file = "summerhouse_price_trend.gif", width = 800, height = 600, delay = 1)

注意点

  • 原单年代码里存在变量名笔误(合并后命名为Municipality07,绘图时调用了Municipality),上述循环代码已修正该问题
  • 你提到需要处理到2020年的话,直接把years <- 2007:2019修改为years <- 2007:2020即可
  • 所有检查用的打印代码如果不需要可以直接注释,运行速度会更快

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 11:48:00