Created
January 15, 2013 23:40
-
-
Save spacedman/4543212 to your computer and use it in GitHub Desktop.
Unstructuring assignments in R...
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
### | |
### unsass.R | |
### | |
### a fairly syntactically clean way of doing unstructuring assignments in R | |
### | |
### syntax: (a~b~c) %=% list(A,B,C) | |
### | |
### not very tested | |
### | |
unsass <- function(lhs,rhs){ | |
nvalues = length(rhs) | |
lhss = getFormulaNames(lhs) | |
if(length(lhss)!=nvalues){ | |
stop("Wrong number of values to unpack") | |
} | |
for(i in 1:nvalues){ | |
eval(substitute(target <- value, | |
list(target=lhss[[i]],value=rhs[[i]])), | |
envir=parent.frame()) | |
} | |
invisible(0) | |
} | |
assign("%=%",unsass) | |
getFormulaNames <- function(formula){ | |
## extract elements from a~b[1]~c~d | |
## recursive - might be an easier way... | |
## | |
if(is.name(formula)){ | |
return(formula) | |
}else{ | |
if(is.call(formula)){ | |
if(formula[[1]]=="~"){ | |
return(c(getFormulaNames(formula[[2]]),getFormulaNames(formula[[3]]))) | |
}else{ | |
return(formula) | |
} | |
} | |
} | |
} | |
## samples | |
## | |
## #1 - the classic swapsie: | |
## | |
## > a=444 | |
## > b=666 | |
## > (a~b) %=% list(b,a) | |
## > a | |
## [1] 666 | |
## > b | |
## [1] 444 | |
## | |
## #2 - elemental, my dear watson: | |
## > a = 1:10 | |
## > b = runif(4) | |
## > (a[4]~b[2]) %=% list(99,102) | |
## > a | |
## [1] 1 2 3 99 5 6 7 8 9 10 | |
## > b | |
## [1] 6.238385e-03 1.020000e+02 1.468159e-01 9.769772e-01 | |
## | |
## #3 - several | |
## > a=1;b=2;c=3;d=4 | |
## > (b~a~d~c) %=% list(a,b,c,d) | |
## > a | |
## [1] 2 | |
## > b | |
## [1] 1 | |
## > c | |
## [1] 4 | |
## > d | |
## [1] 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment