Skip to content

Instantly share code, notes, and snippets.

View xuanlongma's full-sized avatar

Richard Xuanlong Ma xuanlongma

View GitHub Profile
@xuanlongma
xuanlongma / fun_ccfmax.R
Created March 13, 2013 08:10
return the maximum CCF value along with corresponding lag value
## Original arthur: vikrant @ R help mailing list
## return the maximum CCF value along with corresponding lag value
## http://r.789695.n4.nabble.com/ccf-function-td2288257.html
fun.ccfmax <- function(a,b) {
d <- ccf(a, b, plot = FALSE)
cor = d$acf[,,1]
lag = d$lag[,,1]
res = data.frame(cor,lag)
res_max = res[which.max(res$cor),]
@xuanlongma
xuanlongma / fun_fasterstack.R
Last active December 14, 2015 20:08
faster stack raster files
## Thanks RobertH for sharing this very useful function
## http://stackoverflow.com/a/9937083
fun.quickstack <- function(f) {
r <- raster(f[1])
ln <- extension(basename(f), '')
s <- stack(r)
s@layers <- sapply(1:length(f), function(x){ r@file@name = f[x];
r@layernames=ln[x]; r@data@haveminmax=FALSE ; r })
s@layernames <- ln
@xuanlongma
xuanlongma / r_squared.R
Last active December 14, 2015 11:49
compute r^2 values for nonlinear regression model.
## m is the nonlinear model, x is the variable
r2 <- 1 - (deviance(m) / sum((x - mean(x)) ^ 2))
@xuanlongma
xuanlongma / fun_rmse.R
Last active December 14, 2015 11:50
compute RMSE (Root Mean Squared Error)
## RMSE: Root Mean Squared Error
## obs: observations
## pred: predictions
fun.rmse <- function(obs, pred) {
sqrt(mean((obs-pred)^2))
}
@xuanlongma
xuanlongma / shapefile_to_raster.r
Last active December 14, 2015 11:08
convert shapefile to raster
## Convert shapefile to raster
## Packages
require(sp)
require(raster)
## Import shapefile
shp.x = readOGR('shapefile.shp', layer = 'shapefile')
## Create an empty raster
@xuanlongma
xuanlongma / gdal_rasterize.R
Last active December 14, 2015 11:08
invoke system command to convert shapefiles to raster
## invoke system command to convert shapefiles to raster
## Please install gdal before using this snippet
## http://www.gdal.org
## 12000: the width of the output raster
## 6400: the height of the output raster
## layer: the attribute field
system(command = 'gdal_rasterize -a input -ts 12000 6400 -l
layer /Users/me/Desktop/input.shp /Users/me/Desktop/output.tif')
@xuanlongma
xuanlongma / list_files.R
Last active December 14, 2015 11:08
simple expression to get specific files under a directory
## This expression will list all files within the dir.hdf
## directory which contains ‘h29v11’ AND ended with the ‘.hdf’ extension.
files.hdf.h29v11 <- list.files(dir.hdf, pattern = '*.h29v11.*.hdf$',
recursive = TRUE, full.names = TRUE)