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

如何为单数据框中多ID批量运行R脚本并输出Shapefile

批量处理多ID位置数据并导出Shapefile

我有一个包含数千条位置记录的数据框,内含100余个不同ID,每个ID对应60条以上的位置记录。已编写完成处理单个ID并输出Shapefile的R脚本,现需实现自动遍历所有ID执行该脚本的功能。

初始单ID处理脚本

maju<-read.csv("JuvenileRelocations.csv",header=T)
str(maju)
maju$ID <- as.factor(maju$ID)

ma161 <- subset(maju, maju$ID == "1") #subset for 1 id
ma161<-ma161[!is.na(ma161$easting) & !is.na(ma161$northing),]#remove missing locations
##Get only the coordinates
loc <- data.frame("x"=ma161$easting, "y"=ma161$northing)


##Define the projection of the coordinates
proj4string <- CRS("+proj=utm +zone=15 +ellps=WGS84 +datum=WGS84 +units=m +no_defs")

##Make SpatialPointsDataFrame using the XY, attributes, and projection
spdf <- SpatialPointsDataFrame(loc, maju, proj4string = proj4string)

##run the rest of the code using spdf for ID 1 
#####
#####
#####
#final line will be for output shapefile for ID1
writeOGR(hpikde.80vol,dsn="output", layer="ma161plug95",driver="ESRI Shapefile",overwrite=TRUE)

批量处理完整代码

maju<-read.csv("JuvenileRelocations.csv",header=T)
str(maju)
maju$ID <- as.factor(maju$ID)
maju<-maju[!is.na(maju$easting) & !is.na(maju$northing),]
#this to practice on just the first 5 individuals to save computing time
innames<-unique(maju$ID) 
innames<-innames[1:5]
outnames<-innames
##Define the projection of the coordinates
proj4string <- CRS("+proj=utm +zone=15 +ellps=WGS84 +datum=WGS84 
+units=m +no_defs")

for (i in 1:length(innames)){
  data <- maju[which(maju$ID==innames[i]),]
   if(dim(data)[1] != 0){
    #get the coordinates
    data.xy<-data[c("easting", "northing")]
     ##Make SpatialPointsDataFrame using the XY, attributes, and projection
    spdf <- SpatialPointsDataFrame(data.xy, data, proj4string = 
proj4string)
##run the rest of the analysis and export shapefile at end
#####
#####
#####
#write shapefile for each id
writeOGR(hpikde.95vol,dsn = "output", layer=paste(outnames[i], 
"KUD95", sep=""), driver="ESRI Shapefile",overwrite=TRUE)
   }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 21:37:49