Getting weather data from R - Rnoaa

275 views Asked by At

I am trying to get some weather data from rnoaa in R. as rnoaa only supports one year of extraction, I tried to put a loop together to get several years. Is it better to use a map function?

It returns a blank list..

library(rnoaa)
options(noaakey= "somekey") 

washington_weather <- getweather("GHCND:USW00024234")
getweather <- function(stid) {
wtr<-0
for (i in 2009:2017) {
start_date <- paste0(i, "-01-01")
end_date <- paste0(i, "-12-31")
j<- i -2008
wtr[j]$tbl <- ncdc(datasetid='GHCND', stationid=stid, startdate = start_date, enddate = end_date)
}
return(wtr)
}

fahrenheit_to_celsius <- function(temp_F) {
  temp_C <- (temp_F - 32) * 5 / 9
  return(temp_C)
}
2

There are 2 answers

0
Dave2e On

The return value from the ncdc function is a list. Ideally you want to return just the data portion from the list.

In this script, I download each year’s data and save the data portion information in a list. Then one can use the list of data.frames for additional analysis or bind all of the data frames together into one large dataframe.

getweather <- function(stid) {
   wtr<-list()  # create an empty list
   for (i in 2009:2011) {
      start_date <- paste0(i, "-01-01")
      end_date <- paste0(i, "-12-31")
      
      #save data portion to the list (elements named for the year
      wtr[[as.character(i)]] <- ncdc(datasetid='GHCND', stationid=stid, startdate = start_date, enddate = end_date)$data
   }
   #return the full list of data frames
   return(wtr)
}


washington_weather <- getweather("GHCND:USW00024234")

#bind the dataframes in the list together into one large dataframe
dplyr::bind_rows(washington_weather)
0
Colby On

The rnoaa package allows you to combine several ncdc objects that you get from using the package.

If you use ncdc_combine() function, you can combine multiple objects that you create.

For example:

x <- ncdc(datasetid= "GHNCD", stationid=stid, startdate = start_date, enddate = end_date)
y <- ncdc(datasetid= "GHNCD", stationid=stid, startdate = start_date1, enddate = end_date1)

z <- ncdc_combine(x,y)

That will combine your two ncdc objects, as long as you break it down to less than a year for each one.