简体   繁体   中英

How can I save a 3 column data frame into a NetCDF file in R?

I have a Nx3 tibble I'd like to save to a NetCDF (.nc) file. The tibble has three columns:

  1. Longitude (lon)
  2. Latitude (lat)
  3. Data for each point (var)

How can I save this to a NetCDF (.nc) file in R? So far I've been using the raster package with mixed results:

# Be careful to call raster and dplyr in this specific order.
require(raster)
require(dplyr)
set.seed(10)
df <- expand.grid(lon = 1:10, lat=1:10) %>% as_tibble() %>% mutate(var1 = rnorm(100))

val <- df %>% select(var1) %>% pull()

coordinates(df) <- ~ lon + lat
gridded(df) <- TRUE
raster_df <- raster::raster(df)
projection(raster_df) <- CRS("+proj=longlat +datum=WGS84 +ellps=WGS84")
setValues(raster_df, val)
writeRaster(raster_df,
            filename = "file.nc",
            varname = "var1",
            format = "CDF")

The only problem I have with this solution is that it doesn't seem to produce consistent output. Sometimes the files are sometimes corrupted (ie I cannot open them again) and interestingly, they are all the same size which shouldn't be the case at all given that the original data is not all the same (except possibly for longitude and latitude).

I'm using:

  1. R 3.4.1 on Windows 10.
  2. dplyr 0.7.4
  3. raster 2.6-7

I am open to use other alternatives to this approach (or other packages).

Your example seems to go to a lot of unnecessary hoops. Here is a simpler version:

library(raster)
set.seed(10)
r <- raster(xmn=0.5, xmx=10.5, ymn=0.5, ymx=10.5, nrow=10, ncol=10, vals=rnorm(100))
z <- writeRaster(r, filename = "file.nc", varname = "var1")
z

That seems to work fine.

There is one clear mistake in your code: setValues(raster_df, val) . This should be either raster_df <- setValues(raster_df, val) , or values(raster_df) <- val

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM