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

一世执手 提交于 2019-12-11 16:15:54

问题


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 (i.e. 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).


回答1:


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



来源:https://stackoverflow.com/questions/49445214/how-can-i-save-a-3-column-data-frame-into-a-netcdf-file-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!