SiegmundNuyts
SiegmundNuyts

Reputation: 77

Getting data for a specific location from GRIB file

I want to extract data from a GRIB file, provided from ECMWF, for a specific location using R.

For now, I'm able to get data and export it to .csv but the location seems wrong. I'm trying to get it for the south of Ireland (lat/long around 50/-8).

When I read the GRIB file in ArcGIS, the data extracted from R doesn't match the data seen in GIS so I assume I did something wrong with the coordinates.

library(raster)                           
library(tidyverse)
library(lubridate)

s.area <- extent(c(-10.0,-8.5,51.0,51.5))

    s.area@xmin <- s.area@xmin + 180
    s.area@xmax <- s.area@xmax + 180

    output_as_csv <- function(x, ext, var_name="wave_period", start_date, 
                              output_filename) {
      x.out <- data.frame(lon=NA, lat=NA, var_name=NA, date_time=NA)
      x.out <- x.out[FALSE,]
      for(i in 1:nlayers(x)) {
        x.temp <- x[[i]] %>% 
          crop(ext) %>% 
          rasterToPoints() %>% 
          as.data.frame() %>% 
          mutate(date_time=start_date + hours(i) - hours(1),
                 lat=x - 180,
                 lon=y) %>% 
          dplyr::select(-x, -y)
        names(x.temp)[1] <- var_name
        x.out <- rbind(x.out, x.temp)
      }
      x.out <- x.out %>% 
        unite(lon_lat, lon, lat, remove=TRUE) %>% 
        spread(lon_lat, var_name)
      write.csv(x.out, output_filename, row.names=FALSE)
    }

output_as_csv(x=s, ext=s.area, start_date=start.date, output_filename="Wave period.csv")

Upvotes: 1

Views: 2194

Answers (2)

ClimateUnboxed
ClimateUnboxed

Reputation: 8087

You can also extract the value for a specific location directly from the grib file with CDO nearest neighbour remapping with the lon/lat location operator:

cdo remapnn,lon=X/lat=Y input.grb point.grb

If you prefer to have the output in netcdf format you can pipe the answer into the copy command, using the -f format option:

cdo -f nc copy -remapnn,lon=X/lat=Y input.grb point.nc

Upvotes: 1

Andrei Niță
Andrei Niță

Reputation: 619

Every time when I am dealing with grib files I prefer to convert them into netCDF using cdo (cdo -f nc copy infile.grib outfile.nc). Then you can use the raster package in R. I had problems dealing with grib files and raster package in R before.

Upvotes: 2

Related Questions