Как извлечь ячейки сетки модели из файла NetCDF, соответствующие определенным широте и долготе, и отобразить их на одном графике?

Я работаю с R только последние три недели, так что я новичок. В настоящее время я работаю с климатическими данными NetCDF по всей Новой Англии (путь). У меня также есть файл .csv с координатами конкретных городов, которые мы хотим посмотреть (cities.path). Мне удалось извлечь временные годовые временные ряды и тенденции из ячеек сетки модели, соответствующих конкретным городам, из файла .csv. Проблема заключалась в возможности нанести важные городские станции из моего файла .csv на карту со средними годовыми показателями.

Когда я запускаю строку сценария «ave_annual_cities‹ - extract (Annual_ave_stack, cities.points, df = T) », я получаю график широты / долготы с точками моих важных городов. Когда я запускаю «plot (координаты (cities.points))» в консоли, я снова получаю график широты / долготы с моими важными точками городов, однако он стоит отдельно от моего графика ave_annual_cities. Когда я запускаю «levelplot (subset (Annual_ave_stack, 1), margin = F) + layer (sp.points (cities.points, plot.grid = TRUE))», я получаю график Новой Англии со средними годовыми показателями.

Вот мой сценарий.

#Coordinate CS lat/lon pull from Important City Stations
# imports the csv of lat/lon for specific cities
# reads the lat/lon of the .nc modeled climate files
# extracts the time annual time series and trend from model grid cells 
corresponding to your specific cities' locations.
#Graphs City points according to annual time series graph

# Libraries (probably do not need all)
library(survival)
library(lattice)
library(ncdf4)
library(RNetCDF)
library(date)
library(raster)
library(rasterVis)
library(latticeExtra)
library(RColorBrewer)
library(rgdal)
library(rgeos)
library(wux)

path <- "/net/nfs/merrimack/raid/Northeast_US_Downscaling_cmip5/"
vars = c("tasmin","tasmax")
mods = c("ACCESS1-0", "ACCESS1-3",
     "bcc-csm1-1-m", "bcc-csm1-1")
scns = c("rcp45", "rcp85")

cities.path <-
"/net/home/cv/marina/Summer2017_Projects/Lat_Lon/NE_Important_Cities.csv"
necity.vars <- c("City", "State", "Population", "Latitude", "Longitude", 
"Elevation(meters")

#These both read the .csv file (first uses 'utils', second uses 'wux')
#1
cities.read <- read.delim(cities.path, header = T, sep = ",")
#2
read.table <- read.wux.table(cities.path)
cities.read <- subset(cities.read, subreg = "City", sep = ",")

# To test one coordinate point
point_1 <- c("test.city", 44.31, -69.79)
colnames(point_1)<-c("cities", "latitude", "longitude" )

# To read only "Cities", "Latitude", and "Longitude"
cities.points <- subset(cities.read, select = c(1, 4, 5))
cities.points <- as.data.frame(cities.points)
colnames(cities.points)<- c("City", "Latitude", "Longitude" )

#Set plot coordinates for .csv graph
coordinates(cities.points) <- ~ Longitude + Latitude
proj4string(cities.points) <- c("+proj=longlat +datum=WGS84 +ellps=WGS84 
+towgs84=0,0,0") 

# Start loop to envelope all .nc files
for (iv in 1:2){
  for (im in 1:4){
    for (is in 1:2){
      for(i in 2006:2007){
        full<-paste(path, vars[iv], "_day_", mods[im], "_", scns[is], 
"_r1i1p1_", i, "0101-", i, "1231.16th.nc", sep="")
    # this will print out 
    #/net/nfs/merrimack/raid/Northeast_US_Downscaling_cmip5/NameOfFiles.nc

    # this line will print the full file name
    print(full)

    # use the brick function to read the full netCDF file.
    # note: the varname argument is not necessary, but if a file has multiple 
varables, brick will read the first one by default.
    air_t<-brick(full, varname=vars[iv])

    # use the calc function to get an average for each grid cell over the 
entire year
    annual_ave_t<-calc(air_t, fun = mean, na.rm=T)

        if(i == 2006){
          annual_ave_stack = annual_ave_t
        }else{
          annual_ave_stack<-stack(annual_ave_stack, annual_ave_t)
        }  # end of if/else 
      }   # end of year loop
      #extract annual means for grid cells for each year corresponding to 
 important cities
  ave_annual_cities <- extract(annual_ave_stack, cities.points, df = T)
    }   # end of scenario loop
  }   # end of model loop
}  # end of variable loop


levelplot(subset(annual_ave_stack, 1), margin=F) + 
  layer(sp.points(cities.points, plot.grid = TRUE))

# Read lat/lon from .nc climate files
# http://geog.uoregon.edu/bartlein/courses/geog607/Rmd/netCDF_01.htm
climate.data <- nc_open(full)
lat <- ncvar_get(climate.data, varid = "lat")
nlat <- dim("lat")
lat
lon <- ncvar_get(climate.data, varid =  "lon")
nlon <- dim("lon")
lon
  # This gives all lat data. 

#print long and lat variables: confirms the dimensions of the data
print(c(nlon, nlat))


  # If I need time series... 
my.time <- nc_open(climate.data, "time")
n.dates <- trunc(length(climate.data))
n.dates

# open NetCDF choosing pop and lat/lon points
cities.pop.points <- subset(cities.read, select = c(1, 3, 4, 5))
# print NetCDF coordinates with pop
print(cities.pop.points)

Надеюсь, это имеет смысл.


person M. Bow    schedule 16.06.2017    source источник


Ответы (1)


Если ваши входные данные правильно читаются как многополосный растр, вы можете прочитать netcdf как растр, используя:

 r     <- raster::stack(path)
 cells <- raster::cellFromXY(r, xy)
 data  <- raster::extract(r, cells)

, где xy - это матрица координат x / y, которую вы можете легко получить из вашего csv, используя что-то в строках:

 as.matrix(csv_read(cities.path))

HTH

person lbusett    schedule 16.06.2017
comment
У меня проблемы с выражениями: ячейки ‹- raster :: cellFromXY (r, xy) data‹ - raster :: extract (r, cells) Я изменил заголовки широты и долготы в моем файле csv на x и y, и эти выражения все еще не работают. Где они должны быть размещены в моем скрипте и как мне назначить значения для x и y, чтобы при запуске этих строк я не получал ошибку в raster :: cellFromXY (r, xy): объект 'xy' не найден Ошибка в raster :: extract (r, cells): объект 'ячейки' не найдены - person M. Bow; 19.06.2017
comment
Как сообщает сообщение об ошибке, кажется, что xy не определен, поэтому я думаю, что вы неправильно читаете его из файла. Какую инструкцию вы используете? Как писали выше, должно получиться что-то вроде xy = as.matrix(csv_read(cities.path)) - person lbusett; 19.06.2017
comment
Это то, что у меня есть в моем скрипте: r ‹- raster :: stack (full) xy‹ - as.matrix (read.csv (cities.path)) cells ‹- raster :: cellFromXY (cities.path (r, xy )) data ‹- raster :: extract (r, cells), и я получаю сообщение об ошибке: Ошибка в наследовании (xy, SpatialPoints): аргумент xy отсутствует, без значения по умолчанию и другой, Ошибка в растре :: extract (r, cells): объект 'ячейки' не найдены. Спасибо за помощь. - person M. Bow; 19.06.2017
comment
можно попробовать выполнить только xy <- as.matrix(read.csv(cities.path)) и посмотреть, что получится в переменной xy? - person lbusett; 19.06.2017
comment
Спасибо за такое терпение. Когда я распечатываю xy, он дает значение каждой ячейки моего файла csv в матричной форме. Ожидается ли это? - person M. Bow; 20.06.2017
comment
да, я этого и ожидал. Я вижу в вашем коде эту проблемную строку: cells <- raster::cellFromXY(cities.path(r, xy)). должно быть просто cells <- raster::cellFromXY(r, xy) - person lbusett; 20.06.2017
comment
Хм. Я получаю новое сообщение об ошибке, когда пытаюсь запустить эту отредактированную строку. он читает, ›cells‹ - raster :: cellFromXY (r, xy) Ошибка в .doCellFromXY (object @ ncols, object @ nrows, object @ extension @ xmin,: Несовместимо с запрошенным типом: [type = character; target = double ]. - person M. Bow; 20.06.2017
comment
что вы получаете от summary(r)? - person lbusett; 20.06.2017
comment
Я получаю подобное значение для каждого дня в году в 2099 году. X2099.01.01 X2099.01.02 X2099.01.03 X2099.01.04 X2099.01.05 Мин. 262.1193 260.6483 265.0800 261.7262 260.6938 1-й кв. 269,9096 270,7285 271,0857 269,5374 271,0583 - person M. Bow; 20.06.2017
comment
ммм ... очень сложно помочь не видя данных ... Не могли бы вы поделиться csv и одним бэндом nectdf (или ссылкой на него)? - person lbusett; 22.06.2017
comment
см. правки выше. Дайте мне знать, если вам все еще нужна ссылка на CSV. Спасибо - person M. Bow; 23.06.2017