如何将3列数据帧保存到R中的NetCDF文件中? [英] How can I save a 3 column data frame into a NetCDF file in R?

查看:93
本文介绍了如何将3列数据帧保存到R中的NetCDF文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Nx3小节,我想保存到NetCDF(.nc)文件中.标语包含三列:

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

  1. 经度(lon)
  2. 纬度(纬度)
  3. 每个点的数据(var)

如何将其保存到R中的NetCDF(.nc)文件中?到目前为止,我一直在使用 raster 程序包来获得混合结果:

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).

我正在使用:

    Windows 10上的
  1. R 3.4.1.
  2. dplyr 0.7.4
  3. 栅格 2.6-7
  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

这似乎很好.

您的代码中有一个明显的错误:setValues(raster_df, val). 这应该是raster_df <- setValues(raster_df, val)values(raster_df) <- val

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

这篇关于如何将3列数据帧保存到R中的NetCDF文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆