rbind循环中循环命名的文件名

dsekswqp  于 2023-01-22  发布在  其他
关注(0)|答案(1)|浏览(175)

我试图创建一个循环来创建一个 Dataframe ,它包含一个基于10年滚动周期的变量的总和,我想我已经了解了这一点,但是我不知道如何在循环中进行rbind,如果名称也在循环中赋值的话,所以循环只是替换了自己。
虚拟数据设置:

library('dplyr')
library('sf')
library('tigris')

florida <- counties(state = "Florida", year = 2010) %>% 
  select(c(GEOID10)) %>% rename("geoid" = "GEOID10") %>% st_drop_geometry()

florida_annual <- florida %>% mutate(year = 1900, disaster1 = sample(0:5, 67, TRUE), disaster2 = sample(0:5, 67, TRUE) )

for(x in 1901:1990){
  temp <- florida %>% mutate(year = x, disaster1 = sample(0:5, 67, TRUE), disaster2 = sample(0:5, 67, TRUE))
  florida_annual <- rbind(florida_annual, temp)
  rm(temp)
  
}

需要rbinding效果的循环:

for(x in 70){for(j in 1900:1910){
  filename <- paste0("tab_", x)
  assign(filename, florida_annual[florida_annual$year >= j & florida_annual$year <= j + x,] %>% 
           group_by(geoid) %>% 
           summarise(cat_total = sum(disaster1),
                     .groups = 'drop') %>% mutate(year_group = paste0(j,"_", j+x))
  )
}
}
7vux5j2d

7vux5j2d1#

我不清楚你到底想要什么,如果你只是想要一个文件名的 Dataframe ,你只需在循环之前创建一个虚拟 Dataframe ,并在其中创建一个rbind

library('dplyr')
library('sf')
library('tigris')

florida <- counties(state = "Florida", year = 2010) %>% 
  select(c(GEOID10)) %>% 
  rename("geoid" = "GEOID10") %>% 
  st_drop_geometry()

florida_annual <- florida %>%
  mutate(year = 1900, disaster1 = sample(0:5, 67, TRUE), disaster2 = sample(0:5, 67, TRUE) )

for(x in 1901:1990){
  temp <- florida %>% 
    mutate(year = x, 
           disaster1 = sample(0:5, 67, TRUE), 
           disaster2 = sample(0:5, 67, TRUE))
  florida_annual <- rbind(florida_annual, temp)
  rm(temp)
  
}

files <- data.frame()

for(x in 1:70){
  for(j in 1900:1910){
    filename <- paste0("tab_", x)
    assign(
      filename, florida_annual[florida_annual$year >= j & florida_annual$year <= j + x,] %>% 
        group_by(geoid) %>% 
        summarise(cat_total = sum(disaster1),
                  .groups = 'drop') %>% 
        mutate(year_group = paste0(j,"_", j+x))
    )
    files <- rbind(files, filename)
  }
}

相关问题