0
library(weatherData)
for(i in 2003:2016) {

   c <- (getWeatherForYear(station_id = "BOS", year = i))

}

I am writing a loop to get the weather data from year 2003 to year 2016 from the function: getWeatherForYear and combine it into a dataframe

But after looping, dataframe only shows the weather data in year 2016 "not from year 2003 to 2016"

Could someone help me for fixing the loop that will produce a dataframe include the yearly weather data from year 2003 to 2016?

Thanks a lot

Huang
  • 33
  • 3
  • You need a `list` variable to store the output in each run. i.e. `c[[i]] <- ..` if `c <- vector("list", 13)` BTW, `c` is a concatenating function, so it is better to assign object names with something else i.e. `c1` or `cN` etc. – akrun Dec 20 '16 at 09:20
  • Could I know how to write the function if I want to start with c[[i]] <- .. and stack up all the yearly data into a data frame Thank you ! – Huang Dec 20 '16 at 15:36

1 Answers1

0
df <- do.call(
    rbind,
    lapply(
        2003:2016, 
        function(i) getWeatherForYear(station_id = "BOS", year = i)
    )
)
Iaroslav Domin
  • 2,698
  • 10
  • 19
  • for(i in 2003:2005) { h[[i]] <- (getWeatherForYear(station_id = "BOS", year = i)) do.call(rbind, h[[i]]) } – Huang Dec 20 '16 at 14:49
  • Could you kindly explain that why above function does not work as your solution? – Huang Dec 20 '16 at 14:58
  • I'd suggest you to read carefully this SO thread: http://stackoverflow.com/questions/10801750/whats-the-difference-between-lapply-and-do-call-in-r (and documentation of course). – Iaroslav Domin Dec 20 '16 at 15:58