Last active
March 25, 2022 21:57
-
-
Save iago-pssjd/7130e923d5da62adec1d47d12ac29b4a to your computer and use it in GitHub Desktop.
netCDF test with R for a job interview (1st part)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(curl) | |
url = "ftp://.../tas_201711.nc" | |
curl_download(url = url, destfile = "/tmp/tas_201711.nc") | |
# Write a simple R script that | |
## 1. reads the netcdf file | |
as.mon <- function(posixlt){ | |
posixlt <- unclass(posixlt) | |
paste(posixlt[["year"]] + 1900, posixlt[["mon"]] + 1, sep = "-") | |
} | |
library(RNetCDF) | |
netcdfData <- open.nc(con = "/tmp/tas_201711.nc") | |
temp <- var.get.nc(netcdfData, variable = "tas") | |
time_coord2 <- var.get.nc(netcdfData, variable = "time") | |
time_unit2 <- att.get.nc(netcdfData, "time", "units") | |
time_posixct2 <- utcal.nc(time_unit2, time_coord2, "c") | |
time_posixlt2 <- as.POSIXlt(time_posixct2) | |
time_month <- sapply(time_posixlt2, as.mon) | |
# or | |
library(ncdf4) | |
nc_data <- nc_open("/tmp/tas_201711.nc") | |
library(ncdf4.helpers) | |
tas_time <- nc.get.time.series(nc_data, v = "tas", time.dim.name = "time") | |
temp <- ncvar_get(nc_data, "tas") | |
library(PCICt) | |
time_posixlt2 <- as.POSIXlt.PCICt(tas_time) | |
time_month <- sapply(time_posixlt2, as.mon) | |
## 2. computes the monthly mean of the temperature | |
library(parallel) | |
cl <- makeCluster(detectCores() - 2) | |
mean_temp <- parApply(cl, temp, c(1, 2), by, time_month, mean) | |
# Could you create a random R array object with the function array() with 4 dimensions “latitude”, “longitude”, “time”, and “member”, and create an R function to compute the ensemble mean? | |
# The function should work with random order of the dimensions (i.e., “member” can be either of the 1st/2nd/3rd/4th dimension). | |
# If possible, including some initial checks of the inputs in the function. | |
netarray <- array(rnorm(2*3*5*7), dim = c(2,3,5,7), dimnames = list("latitude" = NULL, "longitude" = NULL, "time" = NULL, "member" = NULL)) | |
ensemble_mean <- function(arry, ensemble){ | |
ix <- which(ensemble == names(attr(arry, "dimnames"))) | |
apply(arry, setdiff(1:4, ix), mean) | |
} | |
ensemble_mean(netarray, "member") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment