使用循环提取坐标,匹配坐标并将其写入文件

时间:2019-02-15 14:51:11

标签: r loops for-loop apply sapply

我正在尝试使用for循环(或使用apply函数)从data.frame中提取坐标,在E-OBS {{3}中搜索最近的点},提取时间x1-x2的温度数据,并将其写入另一个excel文件。

虽然代码可以提取单个数据点,但我似乎无法将此代码包含在循环中,也无法将结果添加到输入坐标旁边。

library(sp)
library(raster)
library(ncdf4)

#Coordinates
    df
       ID    site                 E        N
1       1   site_place_date1  7.558758 47.81004
2       2   site_place_date2  7.582749 47.63411
3       3   site_place_date3  7.607968 48.01475
4       4   site_place_date4  7.644660 47.67139
       ...     ...   ...              ...`

手动设置目标点的坐标:

lon <- 7.558758  # longitude of location                
lat <- 47.81004 # latitude  of location

#Mean daily temperature
    ncin <- nc_open("tg_0.25deg_reg_v17.0.nc")
      print(ncin)
      t <- ncvar_get(ncin,"time")
      tunits <- ncatt_get(ncin,"time","units")nt <- dim(t)
      nt
      obsoutput <- ncvar_get(ncin, 
                       start= c(which.min(abs(ncin$dim$longitude$vals -   lon)), # look for closest long
                                which.min(abs(ncin$dim$latitude$vals -  lat)),  # look for closest lat
                                1),
                       count=c(1,1,-1))
      DataMeanT <- data.frame(DateN= t, MeanDailyT = obsoutput)
      nc_close(ncin)
      head(DataMeanT)


#check if there are NAs =999
    summary(DataMeanT)

    Data = DataMeanT
    Data$Date = as.Date(Data$DateN,origin="20000-01-01")
    Data$Year = format(Data$Date,"%Y")
    Data$Month = format(Data$Date,"%m")
    head(Data)
    Data$YearMonth = format(Data$Date, format="%Y-%b")

    Data_annual = aggregate(("T_AnnualMean" = MeanDailyT) ~ Year,data = Data, FUN = mean,na.action = na.pass)
    names(Data_annual)[2] <- "AirT"
    head(Data_annual)

#Export table
    write.table(Data_annual, "Site_AirTemp.csv", row.names = FALSE, append = FALSE, col.names = TRUE, sep = ", ", quote = TRUE)

目标是将脚本作为df中所有坐标的循环的一部分运行,并将温度数据写入包含站点ID信息的新数据表中,或者写入到df的下一列中。

2 个答案:

答案 0 :(得分:0)

由于无法再现,因此很难回答您的问题。但是您可能可以做到:

library(raster)
b <- brick("tg_0.25deg_reg_v17.0.nc")
e <- extract(b, df[, c('E', 'N')])

答案 1 :(得分:0)

将整个过程简单地包装在定义的方法中,并使用 apply 函数传递lon / lat坐标。一个不错的候选者是mapply或其包装器Map,可以在df$Edf$N的两个向量之间逐元素进行迭代。另外,第三个参数df$site传递给具有唯一CSV名称的方法,因为现在该文件将被覆盖。

由于诸如headsummary之类的一些非赋值行在方法内部不起作用,因此将其删除。此外,还使用上下文管理器withinwith来避免重复使用Data$来简化数据操作。 Map调用将写入文件,并建立一个汇总数据帧列表,以备后用。

功能

my_function <- function(lon, lat, site) {    
    # Mean daily temperature
    ncin <- nc_open("tg_0.25deg_reg_v17.0.nc")
      print(ncin)
      t <- ncvar_get(ncin,"time")
      tunits <- ncatt_get(ncin,"time","units")nt <- dim(t)

      # look for closest lon and lat
      obsoutput <- ncvar_get(ncin, 
                             start = c(which.min(abs(ncin$dim$longitude$vals - lon)),
                                      which.min(abs(ncin$dim$latitude$vals - lat)),
                                      1),
                             count = c(1,1,-1))

      DataMeanT <- data.frame(DateN = t, MeanDailyT = obsoutput)
    nc_close(ncin)    

    Data <- within(DataMeanT, {
               Date <- as.Date(DateN, origin="2000-01-01")
               Year <- format(Date,"%Y")
               Month <- format(Date,"%m")
               YearMonth <- format(Date, format="%Y-%b")
            })

    Data_annual <- with(Data, aggregate(list("AirT" = MeanDailyT), list(Year=Year),
                                        FUN = mean, na.action = na.pass))    
    # Export table
    write.table(Data_annual, paste0("Site_AirTemp_", site, "_.csv"), row.names=FALSE,
                append = FALSE, col.names = TRUE, sep = ", ", quote = TRUE)

    # SAVE AGGREGATED DATA FRAME
    return(Data_annual)
}

致电

# ITERATE THROUGH EACH LON/LAT PAIR ELEMENTWISE
df_list <- Map(my_function, df$E, df$N, df$site)

# df_list <- mapply(my_function, df$E, df$N, df$site, SIMPLIFY=FALSE)    # EQUIVALENT CALL