-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathncdf2xyz.R
29 lines (28 loc) · 910 Bytes
/
ncdf2xyz.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
mat2xyz <- function(mat, lon, lat){
#Takes a variable matrix and 2 dimensions vectors and output a XYZ dataframe
lonlat = expand.grid(lon, lat)
sst = as.vector(mat)
data.frame(x=lonlat[,1], y=lonlat[,2], z=sst)
}
ncdf2xyz <- function(file){
#Beware: this version is only adapted to CMIP5 historical data format.
require(ncdf4)
require(raster)
nc = nc_open(file)
tos = ncvar_get(nc, "tos")
time = ncvar_get(nc,"time")
u = ncatt_get(nc,"time")$units
origin = el(regmatches(u,gregexpr("[0-9-]{10}",u)))
time = as.Date(time, origin)
lat = ncvar_get(nc,"rlat")
lon = ncvar_get(nc,"rlon")
lonlat = expand.grid(lon, lat)
sst = as.vector(tos)
sst.mat = matrix(sst, nrow = length(lon)*length(lat), ncol = length(time))
by_day = list()
for(i in seq_along(time)){
by_day[[i]] <- data.frame(cbind(lonlat,sst.mat[,i]))
colnames(by_day[[i]]) <- letters[24:26]
}
by_day
}