簡體   English   中英

使用 R 中的特定條件聚合 nc 文件

[英]Aggregate nc file using specific condition in R

我再次需要你的幫助。 我有 .nc 文件,元數據:文件 minty.nc (NC_FORMAT_64BIT):

 1 variables (excluding dimension variables):
    short mn2t[longitude,latitude,time]   
        scale_factor: 0.000940940342005054
        add_offset: 259.294916797895
        _FillValue: -32767
        missing_value: -32767
        units: K
        long_name: Minimum temperature at 2 metres since previous post-processing

 3 dimensions:
    longitude  Size:57
        units: degrees_east
        long_name: longitude
    latitude  Size:49
        units: degrees_north
        long_name: latitude
    time  Size:90240
        units: hours since 1900-01-01 00:00:00.0
        long_name: time
        calendar: gregorian

2 global attributes:
    Conventions: CF-1.6
    

我有一個代碼,它適用於 smaller.nc 文件:

 library(raster)
 library(rgdal)
 library(ggplot2)
 nc_data = nc_open('file.nc')
 lon = ncvar_get(nc_data, "longitude")
 lat = ncvar_get(nc_data, "latitude", verbose = F)
 t = ncvar_get(nc_data, "time")
 head(lon)
 head(t)
 head(lat)
 mint.array = ncvar_get(nc_data, "mn2t")
 dim(mint.array)
 fillvalue = ncatt_get(nc_data, "mn2t", "_FillValue")
 fillvalue
 mint.array[mint.array == fillvalue$value] <- NA
 r_brick <- brick(mint.array, xmn=min(lat), xmx=max(lat), ymn=min(lon), ymx=max(lon), crs=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs+ towgs84=0,0,0"))
 r_brick = flip(t(r_brick), direction = 'y')

由於文件太大,我得到一個錯誤:“無法分配大小為 1.4 Mb 的向量”我還使用 gc() 清除未使用的 memory。它沒有幫助。 我不需要 file.nc 中的所有數據。 在這種情況下,我需要以某種方式匯總它。 對於我的進一步計算,我只需要每日最小值。 在這種情況下,對於我使用的 df: df(ff) <- aggregate(df, list(rep(1:(nrow(df)%(%n+1), each=24, len=nrow(df))), min)

不幸的是,我發現很難將此代碼改編為 .nc 文件。 也許有人可以幫助我。 先感謝您!

為避免 memory 問題,您可以改為這樣做:

library(raster)
r_brick <- brick('file.nc', "mn2t")

它還可以防止錯誤。 例如,在您的代碼中,這在兩個方面是錯誤的:

xmn=min(lat), xmx=max(lat), ymn=min(lon), ymx=max(lon)

因為x應該是lon並且y應該是lat並且因為 ncdf 坐標指的是單元格的中心,而xmnxmxymnymx指的是邊界。

你也可以使用現代的等價物

library(terra)
r <- rast('file.nc')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM