r - 使用 R 将数据写入 netCDF 文件

标签 r netcdf

我正在尝试使用我自己的 .csv 文件中的数据使用 R 包“ncdf4”创建 netCDF 文件。 我的数据集由 3 列组成:经度、纬度和温度,它有 2592 行。 我一直在按照包中的建议将维度和变量添加到 netCDF 文件中。一切正常,直到我想将温度数据写入我的文件。 我收到这个错误:

Error in ncvar_put(nc = ncnew, varid = var_temp, data, start = c(1, 1,  : 
  ncvar_put: error: you asked to write 65160 values, but the passed data 
  array only has 2592 entries! 

怎么了?

library(ncdf)
library(ncdf4)

TimeTable<-read.csv("time.csv",header=T,sep=",")
filename="time.nc"

xvals<-1:360
yvals<--90:90
nx<-length(xvals)
ny<-length(yvals)
lon1<-ncdim_def("longitude","degrees_east",xvals)
lat2<-ncdim_def("latitude", "degrees_north",yvals )

time<-ncdim_def("Time","months", 1:12, unlim=T )
mv <- -999 # missing value to use
var_temp<- ncvar_def("temperature", "celsius", list(lon1, lat2, time),longname="CRU_Global_1961-1990_Mean_Monthly_Surface_Temperature_Climatology",mv) 


ncnew<-nc_create(filename,list(var_temp))

print(paste("The file has",ncnew$nvars,"variables"))# 
print(paste("The file has",ncnew$ndim,"dimensions"))# 

data<-array(TimeTable$tem_1)
ncvar_put( nc=ncnew, varid=var_temp,data,start=c(1,1,1),count=c(nx,ny,1))

你能给我一些建议吗? 非常感谢

最佳答案

library(ncdf4)

filename="time.nc"

xvals <- seq(-177.5, 177.5, 5)
yvals <- seq(-87.5, 87.5, 5) 
nx <- length(xvals)
ny <- length(yvals)
lon1 <- ncdim_def("longitude", "degrees_east", xvals)
lat2 <- ncdim_def("latitude", "degrees_north", yvals)

time <- ncdim_def("Time","months", 1:12, unlim=TRUE)
mv <- -999 #missing value to use
var_temp <- ncvar_def("temperature", "celsius", list(lon1, lat2, time), longname="CRU_Global_1961-1990_Mean_Monthly_Surface_Temperature_Climatology", mv) 

ncnew <- nc_create(filename, list(var_temp))

print(paste("The file has", ncnew$nvars,"variables"))
#[1] "The file has 1 variables"
print(paste("The file has", ncnew$ndim,"dimensions"))
#[1] "The file has 3 dimensions"

# Some fake dataset based on latitude, to check whether the data are
# written in the correct order
data <- rep(yvals, each=nx)

# Add random -999 value to check whether missing values are correctly
# written
data[sample(1:(nx*ny), 100, replace = FALSE)] <- -999
ncvar_put(ncnew, var_temp, data, start=c(1,1,1), count=c(nx,ny,1))

# Don't forget to close the file
nc_close(ncnew)

# Verification
library(rasterVis)
out <- raster("time.nc")
levelplot(out, margin=FALSE)

enter image description here

关于r - 使用 R 将数据写入 netCDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28949971/

相关文章:

python - 使用python复制netcdf文件

python - 将 xarray 数据变量重新分配给 xarray 坐标

r - 当绘图已经绘制时是否可以更改 ylim 和 xlim ?

r - 如何翻译包裹内容?

Python-计算后重写netcdf文件

python - 使用 Python 将现有 netcdf 文件中的 Nans 替换为 -9999

pandas - 如何将文本文件转换为 netcdf 文件。我有一个气象站 1980 年至 2018 年的观测数据集

r - 在 R 中使用 str_detect() 检测整个单词

r - 将重复的字母转换为数字

java - 使用 Rserve 和 java 并想要计算 t.test。无法将结果返回给java