0

I am trying to create a loop to create a dataframe that has a sum of a variable based on a rolling period of ten years. I think I got that bit figured, but I don't know how to rbind within the loop if the name is also assigned in the loop. So the loop just replaces itself.

dummy data setup:

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)
  
}

Loop that needs an rbinding effect somewhere:

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))
  )
}
} 

1 Answer 1

1

It is unclear to me exactly what you want. If you just want a data frame of file names, you simply create a dummy data frame before your loop and rbind within.

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)
  }
} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.