rfunctionloopsrnoaa

rnoaa air pressure looping


The rnoaa package only allows you to gather 30 days worth of air pressure information at a time https://cran.r-project.org/web/packages/rnoaa/rnoaa.pdf. I'm looking to create a function/ for loop to pull data from the package a month at a time. It's specific the date format that is requires, YYYYMMDD. No - or /. I started with a function, but the lapply, doesn't seem to be applying to the function to call the air pressure data.

I have tried loops in many ways, and I can't seem to get it. Here's an example.

for (i in dates)) {
  air_pressure[i] <- coops_search(begin_date = start[i], end_date = end[i], 
   station_name = 8727520, product= "air_pressure", units = "metric", time_zone = "gmt")
  print(air_pressure[i])
}

start<-seq(as.Date("2015/01/01"), by = "month", length.out = 100)
start <- as.numeric(gsub("-","",start))

end<-seq(as.Date("2015/02/01"), by = "month", length.out = 100)
end <- as.numeric(gsub("-","",end))

pressure_function<- function(air_pressure) { 
     coops_search(station_name = 8727520, begin_date = starting,
               end_date = ending, product = "air_pressure")
}

lapply(pressure_function, starting= start, ending= end, FUN= sum)

No real error messages, just don't populate, or run the function.


Solution

  • There's some pretty fundamental things wrong here. First, your for loop has too many closing parentheses. Second, your lapply call passes a function as the first parameter; that does not work, pass it in the second slot. And more ....

    Anyway, try this:

    library(rnoaa)
    fun <- function(begin, end) {
      coops_search(station_name = 8727520, begin_date = gsub("-", "", begin),
        end_date = gsub("-", "", end), product = "air_pressure")
    }
    start_dates <- seq(as.Date("2015-01-01"), as.Date("2015-12-31"), by = "month")
    end_dates <- seq(as.Date("2015-02-01"), as.Date("2016-01-01"), by = "month") - 1
    res <- Map(fun, start_dates, end_dates)
    df <- dplyr::bind_rows(lapply(res, "[[", "data"))
    head(df)
    #>                     t      v     f
    #> 1 2015-01-01 00:00:00 1025.3 0,0,0
    #> 2 2015-01-01 00:06:00 1025.4 0,0,0
    #> 3 2015-01-01 00:12:00 1025.5 0,0,0
    #> 4 2015-01-01 00:18:00 1025.6 0,0,0
    #> 5 2015-01-01 00:24:00 1025.6 0,0,0
    #> 6 2015-01-01 00:30:00 1025.6 0,0,0
    NROW(df)
    #> [1] 87600