如何更改 R 中的分辨率(或重新网格)数据

use*_*667 5 r data-manipulation cdo-climate

我有一个数据集,由 lon、lat 和涵盖 1961 年至 1970 年的月平均变量(例如温度或降水)组成。该数据集的分辨率为 0.5 x 0.5 度经/纬度,覆盖整个地球,并以 .我使用 R 提取数据的 NC 文件:

library(ncdf)
f <- open.ncdf("D:/CRU/cru_ts3.21.1961.1970.tmp.dat.nc")
A <- get.var.ncdf(nc=f,varid="tmp")
B <- get.var.ncdf(nc=f,varid="lon")
C <- get.var.ncdf(nc=f,varid="lat")
D <- cbind(expand.grid(B, C))
E <- expand.grid(A)
Run Code Online (Sandbox Code Playgroud)

扩展网格(E)是由31,104,000行变量组成的数据表,扩展网格(D)是由259,200行经/纬度组成的数据表。如果乘以 259,200 * 10 年 * 12 个月,您将得到 31,104,000。因此,可以使用以下方法将表 E 分成每月值:

Month <- 1
Start <- (Month-1)*(259200)+1
Finish <- (Month*259200)
G <- E[Start:Finish,]
H <- expand.grid(G)
I <- cbind(D,H) 
Run Code Online (Sandbox Code Playgroud)

因此I现在是第一个月(即1961年1月)的数据表,由lon、lat和变量组成。下面给出了数据示例:

        lon    lat tmp
49184 -68.25 -55.75 7.5
49185 -67.75 -55.75 7.6
49186 -67.25 -55.75 7.6
49899 -70.75 -55.25 6.8
49900 -70.25 -55.25 7.0
49901 -69.75 -55.25 6.9
49902 -69.25 -55.25 7.1
49903 -68.75 -55.25 6.8
49904 -68.25 -55.25 7.6
49905 -67.75 -55.25 8.2
Run Code Online (Sandbox Code Playgroud)

现在我的问题。网格的当前分辨率是 0.5 * 0.5 度,我想“重新网格化”数据,使分辨率为 0.25 * 0.25 度。我不想对数据做任何特别聪明的事情,所以我只希望 0.25 网格获取它所在的 0.5 网格的值,即每个 0.5*0.5 网格包含 4 个 0.25*0.25 网格,我只想要4个0.25*0.25网格与0.5*0.5网格具有相同的值。

我看过光栅,但似乎无法用它做任何事情。

Tro*_*roy 1

这是一种使用的方法plyr::ddply()- 对于您的表大小来说可能会有点慢,具体取决于您想要重新网格化的频率。我会考虑一种使用 data.table 来完成此操作的方法,它应该更快:

require(plyr)
# make your data frame
I<-data.frame(lat=seq(0.5,1000,0.5),lon=1,tmp=sample(1:100,2000,replace=T))

# make an adjustment grid
k<-expand.grid(c(0,0.25),c(0,0.25),0)

# use plyr:ddply() to expand out each entry into the correponding 4 entries
new_I<-ddply(I,.(lat,lon),function(x)as.list(x)+k)
colnames(new_I)<-c("lat","lon","newlat","newlon","tmp")

head(new_I)

  lat lon newlat newlon tmp
1 0.5   1   0.50   1.00  64
2 0.5   1   0.75   1.00  64
3 0.5   1   0.50   1.25  64
4 0.5   1   0.75   1.25  64
5 1.0   1   1.00   1.00  31
6 1.0   1   1.25   1.00  31
Run Code Online (Sandbox Code Playgroud)

实际上考虑一下,从时间角度来看,这是一个更好的方法(尽管它有点黑客,并且让您对将来可能希望进行的额外数据处理的控制较少),但 2m 需要 6.5 秒>> 800 万行。

# make your data frame
I<-data.frame(lat=seq(0.5,1000000,0.5),lon=1,tmp=sample(1:100,2000000,replace=T))

# make an adjustment vector
v<-rep(0.25,times=2000000)

# make 3 new tables, apply the vector appropriately, and rbind
I_latshift<-I
I_lonshift<-I
I_bothshift<-I

I_latshift$lat<-I_latshift$lat+v
I_lonshift$lon<-I_lonshift$lon+v
I_bothshift$lat<-I_bothshift$lat+v
I_bothshift$lon<-I_bothshift$lon+v

I<-rbind(I,I_bothshift,I_latshift,I_lonshift)

# sort it for neatness
I<-I[with(I, order(lat, lon)), ]


head(I)

         lat  lon tmp
1       0.50 1.00   3
6000001 0.50 1.25   3
4000001 0.75 1.00   3
2000001 0.75 1.25   3
2       1.00 1.00  88
6000002 1.00 1.25  88
Run Code Online (Sandbox Code Playgroud)