# reading in CRU files into R
library(raster)
## Loading required package: sp
# for the CRU TS 1.2 download the .zip at
# http://www.cru.uea.ac.uk/cru/data/hrg/timm/grid/CRU_TS_1_2.html
# the raster we get at the end
temp <- brick(nrows = 228, ncols = 258, xmn = -11, xmx = 32, ymn = 34, ymx = 72,
nl = 1200, crs = CRS("+proj=longlat +datum=WGS84"))
# example using the temperature
all_dat <- scan("/home/lionel/Documents/Master/CRU/obs.1901-2000.tmp", skip = 5,
what = "list")
# now only for the temperature of january 1900
xs <- all_dat[seq(2, 37465029, 1203)]
xs <- gsub(",", "", xs)
xs <- as.numeric(xs)
ys <- as.numeric(all_dat[seq(3, 37465029, 1203)])
# put the data in one matrix with first column being the x value, the second
# the y value and the next column the monthly temperature value
mat <- matrix(c(xs, ys), ncol = 2, byrow = FALSE)
numb <- matrix(4:1203, ncol = 1)
numb <- apply(numb, 1, function(x) seq(x[1], 37465029, 1203))
mat <- cbind(mat, apply(numb, 2, function(x) as.numeric(all_dat[x])))
# reverse the rows since they are numbered from bottom to top in CRU and
# from top to bottom in rasters
ys_inv <- ys - ((ys - 113.5) - 1) * 2
mat[, 2] <- ys_inv
# get the cell numbers of each box defined in the CRU dataset
ce <- cellFromRowCol(temp, rownr = mat[, 2], colnr = mat[, 1])
# attribute to these cells the temperature values
values(temp)[ce, ] <- mat[, 3:1202]
values(temp) <- values(temp)/10
# put names to the layers
month <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt",
"Nov", "Dec")
years <- 1901:2000
names(temp) <- paste(rep(month, times = 100), rep(years, each = 12), sep = "_")
# the winter mean temperature between 1914 and 1918
winter_1418 <- calc(temp[[which(names(temp) %in% paste(rep(c("Dec", "Jan", "Feb"),
times = 5), rep(1914:1918, each = 3), sep = "_"))]], mean)
plot(winter_1418)
# the standard deviation in temperature for the years 1901 and 2000
sd_100 <- stack(calc(temp[[grep("1901", names(temp))]], sd), calc(temp[[grep("2000",
names(temp))]], sd))
plot(sd_100)