Last active
November 3, 2017 08:58
-
-
Save mick001/d24a68a37618ca5685781fcdcf4c75e1 to your computer and use it in GitHub Desktop.
How to change the resolution of your spatial data in R? Here's how! Full article at: https://firsttimeprogrammer.blogspot.com/2017/03/resizing-spatial-data-in-r.html
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
# We want more resolution for our data! | |
require(sp) | |
require(ncdf4) | |
require(gstat) | |
require(raster) | |
require(rasterVis) | |
# Clear workspace | |
rm(list=ls()) | |
# Open nc file and get the data | |
a <- nc_open("qnet_2008.nc") | |
qnet <- ncvar_get(a, "qnet") | |
lon <- ncvar_get(a, "lon") | |
lat <- ncvar_get(a, "lat") | |
time <- ncvar_get(a, "time") | |
nc_close(a) | |
# Generate the expanded grid | |
grd <- expand.grid(lon, lat, time) | |
# Set names | |
names(grd) <- c("lon", "lat", "time") | |
# Put the data for qnet in a dataframe | |
vdata <- data.frame(qnet = as.numeric(qnet)) %>% tbl_df() | |
# Bind with the grid | |
data_ <- grd %>% | |
tbl_df() %>% | |
bind_cols(vdata) %>% | |
filter(time == 1) %>% | |
select_("-time") %>% | |
na.omit() | |
# Remove variables not needed anymore | |
rm(a, qnet, lon, lat, grd, vdata, time) | |
# Set coordinates variables | |
coordinates(data_) <- ~ lon + lat | |
gridded(data_) <- TRUE | |
# Interpolation grid. Set a 161x81 grid. | |
data.grid <- expand.grid(lon = seq(310, 350, .25), lat = seq(40, 60, .25)) | |
coordinates(data.grid) <- ~ lon + lat | |
gridded(data.grid) <- TRUE | |
# IDW interpolation | |
idw_out <- idw(qnet ~ 1, locations = data_, newdata = data.grid, nmax = 5) | |
# Plots! | |
# Full data plot. Just for fun. | |
spplot(data_, xlab = "Longitude", ylab = "Latitude", main = "Net heat flux") | |
# Levels for plotting | |
lvls <- pretty(range(data_$qnet), 50) | |
# Actual data | |
r1 <- raster(data_) | |
levelplot(crop(r1, extent(310, 350, 40, 60)), par.settings = RdBuTheme, xlab = "Longitude", ylab = "Latitude", main = "Net heat flux", at = lvls) | |
spplot(crop(r1, extent(310, 350, 40, 60)), xlab = "Longitude", ylab = "Latitude", main = "Net heat flux", at = lvls) | |
# Interpolated data | |
r <- raster(idw_out) | |
levelplot(r, at=lvls, par.settings = RdBuTheme, xlab = "Longitude", ylab = "Latitude", main = "Net heat flux") | |
spplot(r, xlab = "Longitude", ylab = "Latitude", main = "Net heat flux", at = lvls) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment