Home > Mobile >  using for loops with string variables
using for loops with string variables

Time:10-05

I'm using r to download data from an api that uses a key. I've downloaded the data for AK into a df called officials and I would like to download the data for the remaining states using rbind to add each state to the df officials. But the format of the call to the api requires the state abbreviation without ". That is, stateId=AK not "AK". Is there a way to do this? I tried the code below and then realized my error in the GET command specifying stateID. My code inserts "AL" not AL.

states <- c("AL","AR","AZ","CA","CO","CT")

for(i in 1:length(states)) {
  temp_raw <- GET("http://api.votesmart.org/Officials.getByOfficeTypeState?key=xxx&officeTypeId=L&stateId=states[i]&o=JSON")
  my_content <- content(temp_raw, as = 'text')
  my_content2 <- fromJSON(my_content)
  temp_officials <- my_content2$candidate$candidate
  officials2022 <- rbind(officials2022,temp_officials)
  }

CodePudding user response:

Try this variation, using the paste command to combine the strings together into the URL:

Also, notice the simplified way to perform a for loop over states, where i is directly available.

states <- c("AL","AR","AZ","CA","CO","CT")

for(i in states) {
  temp_raw <- paste0("http://api.votesmart.org/Officials.getByOfficeTypeState?key=xxx&officeTypeId=L&stateId=", i, "&o=JSON")
  ...
}
  • Related