同时为多个位置提取时间序列并将它们存储到单独的文件中

时间:2016-12-02 14:15:52

标签: r time-series netcdf

我有一个.txt文件,其中包含许多带有坐标的工作站。因此,.txt文件有三列:一个具有工作站ID,一个带有lat,另一个带有lon,如图所示:

station , lat , lon 
ABTR2100 ,39.13,34.52
GRMR0100 ,20.18,49.00
DDDD0100 ,23.22,46.81
SLPT0100 ,26.91,32.23
NDRT0100 ,29.55,48.97

另外,我有一个.nc文件,其中包含2011年3月的每小时温度数据。.nc文件的结构如下:

2 variables (excluding dimension variables):
    char rotated_pole[]   
        grid_mapping_name: rotated_latitude_longitude
        grid_north_pole_latitude: 39.25
        grid_north_pole_longitude: -162
    float var11[rlon,rlat,height,time]   
        table: 2
        grid_mapping: rotated_pole
 4 dimensions:
    rlon  Size:848
        standard_name: grid_longitude
        long_name: longitude in rotated pole grid
        units: degrees
        axis: X
    rlat  Size:824
        standard_name: grid_latitude
        long_name: latitude in rotated pole grid
        units: degrees
        axis: Y
    height  Size:1
        standard_name: height
        long_name: height
        units: m
        positive: up
        axis: Z
    time  Size:744   *** is unlimited ***
        standard_name: time
        units: hours since 2011-02-28 18:00:00
        calendar: proleptic_gregorian

我想要做的是为每个时间步骤提取.txt文件中包含的每个工作站的时间序列,并将时间系列存储到一个单独的.txt文件中,该文件将具有工作站ID的名称。所以,这意味着我将有一个名为“ABTR2100_temp”的.txt文件,它将包含该特定位置的时间序列。所有电台都会发生同样的情况。我可以在R吗?

1 个答案:

答案 0 :(得分:1)

将您的工作站坐标读取为数据框。禁止将站名转换为因子禁用stringsAsFactor参数。

yourstations <- read.csv("yourstations.txt", stringsAsFactor = FALSE)

借助ncdf4包将您的数据作为连接加载到工作区中。检查一切都好吗?

library(ncdf4)
nc.filename <- "yourdata.nc"
yourconn.nc <- nc_open(nc.filename)
yourconn.nc

获取网格纬度和经度的值。

lon <- ncvar_get(yourconn.nc,"rlon")
lat <- ncvar_get(yourconn.nc,"rlat")

对站的每一行数据帧使用for循环。使用for循环找到最接近的纬度和经度,并根据行列号获取一个网格点(sta.temp)的所有值。用电台名称写。

for(ttnum in 1:nrow(yourstations)){
    ## Find the closes lat    
    lat.diff <- abs(lat - yourstations[ttnum, "lat"])
    lat.nr <- which(lat.diff == min(lat.diff))[1]
    ## Find the closes lon
    lon.diff <- abs(lon - yourstations[ttnum, "lon"])
    lon.nr <- which(lon.diff == min(lon.diff))[1]
    ## Copy data of the gridpoint
    sta.temp <- ncvar_get(yourconn.nc, "var11",  c(lon.nr,lat.nr,1,1),c(1,1,1,744))
    ## Write the vector
    write(sta.temp, file = paste0(yourstations[ttnum, "station"],"_temp.txt"), ncol = 1)
}

我不确定您是否可以使用旋转坐标顺畅地工作(请参阅问题Extracting site-specific information from NetCDF file in R netcdf4 raster使用的$sql = "SELECT id FROM table WHERE column IN ('data1','data2')" ; $result = mysqli_query($db, $sql); $data = array(); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { array_push($data,$row['id']); } } else { echo "0 results"; } echo $data; 包。)