Search code examples
rapiloops

Loop in R is only adding the first and last set of data to dataframe


I'm trying to loop through an API, to get data from specific sitecodes and merge it into one dataframe, and for some reason the following code is only getting the original dataframe (RoyalLondon_List) and the last sensor (CDP0004)

SiteCodes_all <- c('CLDP0002', 'CLDP0003', 'CLDP0004')

for(i in 1:length(SiteCodes_all)) {
  
        allsites <- paste0(Base,Node,SiteCodes_all[i],'/',Pollutant,StartTime,EndTime,Averaging,Key)
  
        temp_raw <- GET(allsites)
        temp_list <- fromJSON(rawToChar(temp_raw$content))
        df <- rbind(RoyalLondon_List, temp_list)
  
}

Any help appreaciated!

The above code combines the previous data and not the looped API url


Solution

  • Try use this

    df <- RoyalLondon_List
    
    for(i in 1:length(SiteCodes_all)) {
      
            allsites <- paste0(Base,Node,SiteCodes_all[i],'/',Pollutant,StartTime,EndTime,Averaging,Key)
      
            temp_raw <- GET(allsites)
            temp_list <- fromJSON(rawToChar(temp_raw$content))
            df <- dplyr::bind_rows(df, temp_list)
      
    }
    

    dplyr::bind_rows() is a function in the dplyr package that allows you to combine multiple dataframes by appending the rows of one dataframe to the bottom of another.see here to more info about it.