如何将3列数据帧保存到R中的NetCDF文件中?

时间:2022-09-06 17:03:29

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

我有一个Nx3 tibble我想保存到NetCDF(.nc)文件。 tibble有三列:

  1. Longitude (lon)
  2. Latitude (lat)
  3. Data for each point (var)
  4. 每个点的数据(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:

如何将其保存到R中的NetCDF(.nc)文件?到目前为止,我一直在使用具有混合结果的光栅包:

# 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. Windows 10上的R 3.4.1。

  3. dplyr 0.7.4
  4. raster 2.6-7

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

我愿意使用这种方法(或其他包)的其他替代方案。

1 个解决方案

#1


2  

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

你的代码中有一个明显的错误:setValues(raster_df,val)。这应该是raster_df < - setValues(raster_df,val)或值(raster_df)< - val

#1


2  

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

你的代码中有一个明显的错误:setValues(raster_df,val)。这应该是raster_df < - setValues(raster_df,val)或值(raster_df)< - val