Last active
August 29, 2015 14:01
-
-
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
This file contains hidden or 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
# 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) |
This file contains hidden or 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
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