library(data.table)
df <- read.csv()###input data
# transform to data.table（if not）
dt <- as.data.table(df)

# select the gridcell that wetland prensent more than 80%
wetlands <- dt[wetland_prent_2020 >= 0.8]


results_list <- list()
result_index <- 1L


setkey(dt, Row, Colum)

#adaptive moving search window
for (i in 1:nrow(wetlands)) {
  print(i)
  #i <- 2
  w <- wetlands[i]
  w_row <- w$Row
  w_col <- w$Colum
  w_ele <- w$`global_dem_data_3min.tif`
  
  found <- FALSE
  
  # from window 1 to window 9, window 1 represent 0.15°*0.15°，window 9 represent 0.95°*0.95°
  for (r in 1:9) {
    row_range <- (w_row - r):(w_row + r)
    col_range <- (w_col - r):(w_col + r)
    
    # use fast subset
    neighbors <- dt[Row %in% row_range & Colum %in% col_range & forest_prent_2020 > 0.8]
    
    if (nrow(neighbors) > 0) {
      neighbors[, elev_diff := abs(`global_dem_data_3min.tif` - w_ele)]
      valid_neighbors <- neighbors[elev_diff <= 100]
      
      if (nrow(valid_neighbors) > 0) {
        # creat result record
        results_list[[result_index]] <- data.table(
          wetland_Row = w_row,
          wetland_Colum = w_col,
          wetland_Tmean = w$`Tmean_2020.tif`,
          wetland_allskyTs = w$`allskyTs_2020.tif`,
          forest_Row = valid_neighbors$Row,
          forest_Colum = valid_neighbors$Colum,
          forest_Tmean = valid_neighbors$`Tmean_2020.tif`,
          forest_allskyTs = valid_neighbors$`allskyTs_2020.tif`,
          forest_prent = valid_neighbors$forest_prent_2020,
          window_code = r,
          window_number = nrow(valid_neighbors)
        )
        result_index <- result_index + 1L
        found <- TRUE
        break
      }
    }
  }
}
# merge all result
result_dt <- rbindlist(results_list)