Search code examples
rloopscensus

Trouble looping through function in R


I am trying to loop through a function in R. I want to loop through 62 stored values but the loop only seems to run and save for the last output. I am new to loops and think this may be an easy fix

my stored vales are:

    state_county
state:36+county:015
state:36+county:063
state:36+county:007
state:36+county:081
state:36+county:055

my code is:

    for (i in state_county)
{
  test <-  getCensus(name = "acs/acs5",
               vintage = 2016, 
               vars = c("NAME", "B19013_001E"), 
               region = "Block Group:*", 
               regionin = i)
}

'regionin' must be in format: state:""+county:""

The end result will only return a data frame for state:36+county:055 (the last value in my stored value set


Solution

  • It's a bit difficult to give a full answer when reproducible data is not present. However, what happens is that you keep saving your new calculation over and over under the same variable.

    I created a list variable results which will save the outputs of each iteration . Given that state_county is some kind of a list or vector, I used length to find out how long it is. Next, I iterate over each item starting with one and saving the test variable inside results.

    results <- list()
    for (i in 1:length(state_county)))
    {
      test <-  getCensus(name = "acs/acs5",
                         vintage = 2016, 
                         vars = c("NAME", "B19013_001E"), 
                         region = "Block Group:*", 
                         regionin = state_county[[i]])
      
      results[[i]] <- test
    }