1 |
7526fb1c
|
Jim Regetz
|
##
|
2 |
|
|
##
|
3 |
|
|
##
|
4 |
|
|
|
5 |
|
|
rm(list=ls(all=TRUE))
|
6 |
|
|
|
7 |
|
|
setwd("C:\\Users\\Frank\\Documents\\Data\\Climate_data\\CRU_TS_3.0")
|
8 |
|
|
|
9 |
|
|
library(ncdf)
|
10 |
|
|
|
11 |
|
|
vrb<-c("pre","tmn","tmp","tmx")
|
12 |
|
|
for(v in 4:4){
|
13 |
|
|
# open data file
|
14 |
|
|
nc<-open.ncdf(paste("cru_ts_3_00.1901.2006.",vrb[v],".nc",sep="")) # open datafile
|
15 |
|
|
|
16 |
|
|
nodata<-nc$var$tas$missval # nodata value
|
17 |
|
|
time.dim<-nc$dim$time$len # time dimension
|
18 |
|
|
time.base<-as.numeric(substr(nc$dim$time$units,14,17)) # base year
|
19 |
|
|
time.start<-round(nc$dim$time$vals[1]/12)+time.base # year simulation started
|
20 |
|
|
time.end<-floor(nc$dim$time$vals[time.dim]/12)+time.base # year simulation ended
|
21 |
|
|
|
22 |
|
|
# build flip matrix
|
23 |
|
|
I<-matrix(0,360,360)
|
24 |
|
|
y<-360
|
25 |
|
|
for(x in 1:360){
|
26 |
|
|
I[x,y]<-1
|
27 |
|
|
y<-y-1
|
28 |
|
|
}
|
29 |
|
|
|
30 |
|
|
## extract data for 1968 to 2006 and output as ESRI ASCII files
|
31 |
|
|
for(i in 1:time.dim){
|
32 |
|
|
# define year and month
|
33 |
|
|
if(trunc(i/12)!=i/12){
|
34 |
|
|
year<-floor(i/12)+time.start
|
35 |
|
|
month<-round((i/12-trunc(i/12))*12)
|
36 |
|
|
}else{
|
37 |
|
|
year<-floor(i/12)+time.start-1
|
38 |
|
|
month<-12
|
39 |
|
|
}
|
40 |
|
|
if(year<2005) next
|
41 |
|
|
|
42 |
|
|
# read data
|
43 |
|
|
ncd<-get.var.ncdf(nc,start=c(1,1,i),count=c(720,360,1))
|
44 |
|
|
|
45 |
|
|
# flip matrix
|
46 |
|
|
grd<-I%*%(t(ncd))
|
47 |
|
|
|
48 |
|
|
# ouput to file in ESRI ASCII format
|
49 |
|
|
esri<-c(paste("ncols",720),
|
50 |
|
|
paste("nrows",360),
|
51 |
|
|
paste("xllcorner",-180),
|
52 |
|
|
paste("yllcorner",-90),
|
53 |
|
|
paste("cellsize",0.5),
|
54 |
|
|
paste("nodata_value",-99.9))
|
55 |
|
|
path2<-paste("cru_ts_3.0_",vrb[v],"_",year,"_",month,".asc",sep="")
|
56 |
|
|
write.table(esri,path2,row.names=F,col.names=F,quote=F,append=F)
|
57 |
|
|
write.table(data.frame(grd),path2,row.names=F,col.names=F,quote=F,append=T)
|
58 |
|
|
}
|
59 |
|
|
close.ncdf(nc) # close datafile
|
60 |
|
|
}
|
61 |
|
|
|