简体   繁体   English

从 NETCDF R 生成时间序列向量(空间平均值)

[英]Generate timeseries vector (spatial average) from NETCDF R

I have a NETCDF file with attributes being lon,lat,time,precipitation.我有一个 NETCDF 文件,其属性为 lon、lat、time、precipitation。 The data covers a certain spatial domain.数据覆盖一定的空间域。 It is daily data from 1960 to 2100.它是从 1960 年到 2100 年的每日数据。

1) I will like to subset the data spatially (eg lat[45,50] and lon[-78,-85])from the main domain 1)我想从主域中对数据进行空间子集化(例如 lat[45,50] 和 lon[-78,-85])

2) From the subset, I will like to average over all grids and produce a single column daily time series then write it to a .csv file. 2)从子集中,我想对所有网格求平均值并生成单列每日时间序列,然后将其写入 .csv 文件。

NB: my data contains missing values注意:我的数据包含缺失值

Something along these lines ought to work沿着这些路线的东西应该起作用

library(raster)
b <- brick('file.nc')
be <- crop(b, extent(-85, -78, 45, 50))
a <- aggregate(be, dim(be)[2:1], na.rm=TRUE)
v <- values(a)
write.csv(v, 'precip.csv', row.names=FALSE)

Normally, to get the date as well:通常,还要获取日期:

date <- getZ(be)

Or或者

date <- names(a)
date <- gsub('X', '', date)

And then进而

v <- data.frame(date=date, prec=v)
write.csv(v, 'precip.csv', row.names=FALSE)

Whether or not this date is human readable depends on how it is stored in the ncdf file (ie whether certain conventions are followed or not).这个日期是否是人类可读的取决于它如何存储在 ncdf 文件中(即是否遵循某些约定)。

This would do the cut and the averaging but writes the answer to another netcdf.这将进行切割和平均,但将答案写入另一个 netcdf。 If you really need CSV, then you would need to use that part of the solution above.如果您确实需要 CSV,那么您将需要使用上述解决方案的那部分。

cdo fldmean -sellonlatbox,-85,-78,45,50 in.nc out.nc
library (ncdf4)

nc <- nc_open("netcdf.nc")

lon <- ncvar_get(nc,"lon")
lat <- ncvar_get(nc,"lat")
time <- ncvar_get(nc,"time")

lon_lim <- c(45,50)
lat_lim <- c(-78,-85)

lon_ind <- which(lon >= lon_lim[1] & lon <= lon_lim[2])
lat_ind <- which(lat >= lat_lim[1] & lat <= lat_lim[2])

precip <- ncvar_get(nc,"precip",start = c(lon_ind[1],lat_ind[1],time),count = c(length(lon_ind),length(lat_ind),length(time)))

ts <- apply(precip,3,mean,na.rm=TRUE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM