r语言 - 创建一个循环来子集数据和合并空间数据映射以创建gif



大家好

谁能帮我做一个循环对于下面的代码?我基本上通过从Excel数据和每年的shapefile中合并创建新地图来创建动态mac/gif,然后将所有地图合并为gif。所有这些工作已经,但我想知道如果代码可以通过循环函数完成。但是,我真的对他们一无所知,搞不懂

数字1:子集数据

summerhouses2007<-summerhouseprices[,c("Kommune",'2007')] #07
summerhouses2008<-summerhouseprices[,c("Kommune",'2008')] #08
summerhouses2009<-summerhouseprices[,c("Kommune",'2009')] #09
summerhouses2010<-summerhouseprices[,c("Kommune",'2010')] #10
summerhouses2011<-summerhouseprices[,c("Kommune",'2011')] #11
summerhouses2012<-summerhouseprices[,c("Kommune",'2012')] #12
summerhouses2013<-summerhouseprices[,c("Kommune",'2013')] #13
summerhouses2014<-summerhouseprices[,c("Kommune",'2014')] #14
summerhouses2015<-summerhouseprices[,c("Kommune",'2015')] #15
summerhouses2016<-summerhouseprices[,c("Kommune",'2016')] #16
summerhouses2017<-summerhouseprices[,c("Kommune",'2017')] #17
summerhouses2018<-summerhouseprices[,c("Kommune",'2018')] #18
summerhouses2019<-summerhouseprices[,c("Kommune",'2019')] #19

第二步:创建、保存和合并gif格式的地图

####checking the summerhouse prices for 2007+ structure######
dim(summerhouses2007)
str(summerhouses2007$Kommune)
str(summerhouses2007$`2007`)
###so we know the "Kommune" variable - character; "2007" variable - numeric###
####merging excel data with shapefile map over municipalities####
kommune$KOMNAVN<-gsub(" Kommune","",kommune$KOMNAVN)
Municipality07<-merge(kommune, summerhouses2007, 
by.x=c("KOMNAVN"), by.y=c("Kommune"),all=FALSE)
####checking######
head(Municipality$`2007`)
#### making price intervals#####
p_intervals <- classIntervals(Municipality07$'2007', 5, style="fixed", 
fixedBreaks=c(0,1,10000,20000,30000,40000))
####choosing colors according to intervals ####
p_Colours <- findColours(p_intervals,sequential_hcl(5, palette="Reds2"))
####################################################################
### but here we just save them as png files in to the saving path###
###save the 2007.png file########
png(filename="2007.png")
plot(sea,col="cadetblue3")
plot(kommune, col= "beige",add=TRUE)
plot(Municipality, axes=TRUE, col=p_Colours, add=TRUE)
####Adding legend #####
legend("topright", 
fill = attr(p_Colours, "palette"), 
border="black", 
legend=gsub(",", " - ", names(attr(p_Colours, "table"))), 
bg ="white",
title="Summerhouse prices 2007") 
##### saving the map  #######
dev.off()

从2007年到2020年,一切都是重复的。

欢呼:)

如果您已经学会编写问题中的所有代码,那么您当然能够学习如何使用for循环。你能做到的!

我建议尝试一个简单的循环来弄清楚发生了什么。例如,尝试使用元素本身遍历vector中的元素。

fruits <- c("apple", "peach", "pear")
for(fruit in fruits){
print(fruit)
}

你也可以使用他们的索引

fruits <- c("apple", "peach", "pear")
# Return second element in vector
fruits[2]
for(i in 1:length(fruits)){
print(fruits[i])
}

你可以这样读你的数据,每年一次。我可以想象,您可能希望所有的代码都在循环的每次迭代中进行操作。

years <- 2007:2019
for(year in years){
house <- summerhouseprices[,c("Kommune", year)]
}

更多关于循环的信息:https://www.r-bloggers.com/2015/12/how-to-write-the-first-for-loop-in-r/

最新更新