我对R比较陌生。 我试图从netCDF文件中获取温度数据的不同点(lat,lon)的时间序列。 我的示例数据文件是here,here是小文件。我已经尝试过netCDF包和我到目前为止使用的代码
library(ncdf)
obsdata = open.ncdf("obs.nc")
print.ncdf(obsdata)
obsdatadates = obsdata$dim$time$vals
obsdatadates = as.Date(obsdatadates,origin = '1950-01-01')
obsdatadates
obsoutput = get.var.ncdf(obsdata, varid = 'tasmin', start = c(1,1,1),
count = c(1,1,22280))
dim(obsoutput)
datafinal=merge(obsdatadates,obsoutput)
任何人都可以帮助我获取该数据的特定点(纬度,经度)的时间序列数据帧(第一列)和另一个数据值。 在这种情况下,我正在寻找特定纬度点(并重复多个兴趣点)和给定变量(在这种情况下)的时间序列(1950-01-01至2010-12-31,其中数据为) tasmin)。 非常感谢您的帮助。 谢谢, aseem
答案 0 :(得分:7)
也许使用raster
包,这不适用于所有NetCDF文件,但它适用于您的:
library(raster)
## brick reads all 22280 layers
r <- brick("obs.nc", varname = "tasmin")
## extract works for all time steps
vals <- extract(r, matrix(c(-120, 52.5), ncol = 2))
dim(vals)
## [1] 1 22280
注意,给出一个1行,多列矩阵,因为我只给了extract()
一个点。
(从最近的单元格直接复制,提取很简单,使用method =“bilinear”进行插值)。有关其他选项,请参阅?extract
。
答案 1 :(得分:4)
以下是我将如何使用ncdf
:
library(ncdf)
obsdata = open.ncdf("obs1.nc")
obsdatadates = as.Date(obsdata$dim$time$vals,origin = '1950-01-01')
#Get the whole data first
obsoutput = get.var.ncdf(obsdata, varid = 'tasmin')
#Prepare your points of interest
points_of_interest = data.frame(lat=seq(1,8,by=2),lon=c(1,5,3,6))
#Subset your data accordingly
data_at_point = apply(points_of_interest,1,function(x)obsoutput[x[1],x[2],])
#Turn it into a dataframe
data_at_point = as.data.frame(data_at_point)
#Add the dates to the dataframe
data_at_point$Date = obsdatadates
答案 2 :(得分:2)
不推荐使用&#39; ncdf&#39; -package:http://cirrus.ucsd.edu/~pierce/ncdf/
使用ncdf4包进行更新:
library(ncdf4)
obsdata <- nc_open("obs1.nc")
print(obsdata) # check that dims are lon-lat-time
# location of interest
lon <- 6 # longitude of location
lat <- 51 # latitude of location
# get dates
obsdatadates <- as.Date(obsdata$dim$time$vals, origin = '1950-01-01')
# get values at location lonlat
obsoutput <- ncvar_get(obsdata, varid = 'tasmin',
start= c(which.min(abs(obsdata$dim$longitude$vals - lon)), # look for closest long
which.min(abs(obsdata$dim$latitude$vals - lat)), # look for closest lat
1),
count = c(1,1,-1)) #count '-1' means 'all values along that dimension'that dimension'
# create dataframe
datafinal <- data.frame(dates= obsdatadates, obs = obsoutput)