自动组合R中的数据帧

automize combining data frames in R

我首先创建了我的数据框的两个子集,如下所示:

a = read_sf("a.shp")
a = st_make_valid(a)

#creating first subset with polygons from base year 2000
a1 = subset(a, year==2000)

#creating second subset with polygons from all the following years
a2 = subset(a, year>2000)

#creating buffer around base year
buffer = st_buffer(a1, 500)

#intersection of buffer from base year with polygons from the following years 
#(lets assume the column "year" in the data.frame has a range of years 2000-2010)
results2000 = st_intersection(buffer, a2)

我现在必须在接下来的每一年都执行这些步骤,直到 2010 年。所以下一个结果将如下所示:

a = read_sf("a.shp")
a = st_make_valid(a)

#creating first subset with polygons from base year 2000
a1 = subset(a, year==2001)

#creating second subset with polygons from all the following years
a2 = subset(a, year>2001)

#creating buffer around base year
buffer = st_buffer(a1, 500)

#intersection of buffer from base year with polygons from the following years 
#(lets assume the column "year" in the data.frame has a range of years 2000-2010)
results2001 = st_intersection(buffer, a2)

唯一更改的条目是子集代码中的年份。

最后,我需要一个 data.frame 包含所有 10 个结果(合并 results2000 到 results2010,每个结果都以 2000 年到 2010 年之间的 10 年中的一年作为基准年)。

我可以创建所有 10 个结果并通过

组合它们
rbind(results2000,results2001,...) 

等等。

但是他们这样做更简单吗? 我考虑过使用 foreach 包中的 foreach 函数,可能是这样的

但是使用 foreach 创建循环会导致绘图时间非常长,因为 data.frame“a”包含大约 100 万行。

有人能帮忙吗?

我不知道你用哪个包来获取数据,所以我假设 st_intersection(buffer, a2) 的输出来回答是一个dataframe(因为你说你想使用rbind)。

如果是这种情况,您可以创建一个空列表(我在下面称为 outlist),然后循环填充该列表,最后,将列表的不同元素绑定在一起。

查看下面的代码:

a = read_sf("a.shp")
a = st_make_valid(a)


# Define your cutting year 
subset_yr <- 2000:2010
# Create an empty list you will populate
outlist <- vector(mode = "list", length = length(subset_yr))

# Your code in a loop
for(i in seq_along(subset_yr)) {
  #creating first subset with polygons from base year i (2000, 2001, etc.)
  a1 = subset(a, year==subset_yr[i])
  
  #creating second subset with polygons from all the following years
  a2 = subset(a, year>subset_yr[i])
  
  #creating buffer around base year
  buffer = st_buffer(a1, 500)
  
  #intersection of buffer from base year with polygons from the following years 
  outlist[[i]] = st_intersection(buffer, a2)
  
  #Add a column indicating the year
  outlist[[i]]$Year <- subset_yr[i]
}

# Bind everything together
rbind(outlist)