问题
I have a Nx3 tibble I'd like to save to a NetCDF (.nc) file. The tibble has three columns:
- Longitude (lon)
- Latitude (lat)
- 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:
- R 3.4.1 on Windows 10.
- dplyr 0.7.4
- 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