gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:20:09 31 4
gpt4 key购买 nike

我有一个由 lon、lat 和一个涵盖 1961 年到 1970 年的月平均变量(例如温度或降水)组成的数据集。该数据集的分辨率为 0.5 x 0.5 度 lon/lat,覆盖整个地球,并作为 .我使用以下方法提取了 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)

扩展网格 (E) 是一个包含 31,104,000 行变量的数据表,扩展网格 (D) 是一个包含 259,200 行 lon/lat 的数据表。如果你乘以 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)

因此,我现在是第一个月(即 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

现在我的问题。网格的当前分辨率为 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 网格具有相同的值。

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

最佳答案

这是一种使用 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

实际上考虑一下,从时间的角度来看,这是一个更好的方法(虽然它有点hack,并且使您对将来可能希望进行的其他数据处理的控制更少),但是2m需要6.5秒>> 8M 行。
# 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

关于r - 如何更改 R 中的分辨率(或重新网格)数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21152308/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com