Skip to content

Instantly share code, notes, and snippets.

View lgatto's full-sized avatar

Laurent Gatto lgatto

View GitHub Profile
@lgatto
lgatto / getVariableName.R
Created May 15, 2012 19:06
Grab a variable names passed as function parameter
##' Return the name of variable \code{varname} in call \code{match_call}.
##'
##' @title Return a variable name
##' @param match_call An object of class \code{call}, as returned by \code{match.call}.
##' @param varname An \code{character} of length 1 which is looked up in \code{match_call}.
##' @return A \code{character} with the name of the variable passed as parameter
##' \code{varname} in parent close of \code{match_call}.
@lgatto
lgatto / watch_variable.R
Created May 13, 2012 20:40
Monitor a variable in R
## Credit Hadley Wickham
## http://www.mail-archive.com/[email protected]/msg125980.html
watch <- function(varname) {
old <- get(varname)
changed <- function(...) {
new <- get(varname)
if (!identical(old, new)) {
message(varname, " is now ", new)
old <<- new
}
@lgatto
lgatto / speed.R
Created March 5, 2011 13:44
Comparing for, apply and vectorised functions
m <- matrix(runif(1e6),nrow=10000)
## append to result vector -- slow
res1 <- NULL
t1 <- system.time(for (i in 1:1000) res1[i] <- sum(m[i,]))
## initialise to full length -- fast
res2 <- numeric(1000)
t2 <- system.time(for (i in 1:1000) res2[i] <- sum(m[i,]))
@lgatto
lgatto / listORenv.R
Created November 25, 2010 17:15
Comparing speed when populating an environment and a preallocated list
library(MSnbase)
n <- 10000
ll <- vector("list",length=n)
e <- new.env()
tl <- system.time(for (i in 1:n)
ll[[i]] <- new("Spectrum2"))
te <- system.time(for (i in 1:n)
assign(paste("X",i,sep=""),new("Spectrum2"),e))
## Results for n=10000