Skip to content

Instantly share code, notes, and snippets.

@MrFlick
Last active August 29, 2015 14:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrFlick/35ff2265619762d49159 to your computer and use it in GitHub Desktop.
Save MrFlick/35ff2265619762d49159 to your computer and use it in GitHub Desktop.
withX.R: Allows you to perform multiple operations on a temporary object without having to create a temporary variable
# withX() will create an environment for the first parameter and all of your named parameters
# if the first parameter is not named, it will be called "X" in the enviroment
# there may be exactly one unnamed expression
# this unnamed parameter will be eval'ed in the envir defined by your named parameters
# If no object is returned from the expression, the newest value of the first parameter is returned invisibly
# this can avoid repeating awkward expressions
#this is a lot like `with()` but instead of working within the variable,
# the value itself is added to the enviroment as a variable
withX(data.frame(a=1:3), cbind(X, "ok")
withX(Q=data.frame(a=1:3), for(i in 1:3) {Q$a<-Q$a+1})
withX(a=1, b=3, a+b)
withX(lm(y~x, data.frame(x=runif(10), y=runif(10))), c(coef(X), rsq=summary(X)$r.squared))
plot(g, edge.width=withX(E(g)$weight, (X-min(X))/(max(X)-min(X))*10)
withX <- function(..., returnSelf=is.null(r)) {
args<-as.list(substitute(list(...)))[-1L]
stopifnot(length(args)>1)
if(is.null(names(args))) {
names(args)<-c("X", rep("", length(args)-1))
}
stopifnot(sum(names(args)=="")==1)
env <- new.env()
for(i in which(names(args)!="")) {
assign(names(args)[i], eval(args[[i]], parent.frame() ), envir=env)
}
r<-eval(args[[which(names(args)=="")]], env, parent.frame())
if(returnSelf) {
invisible(get(names(args)[1], env))
} else {
r
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment