An embedded and charset-unspecified text was scrubbed... Name: not available URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20130314/4485bdeb/attachment.pl>
Equivalent of deal in R?
4 messages · Sahana Srinivasan, Ista Zahn, Marc Schwartz +1 more
Maybe
x <- array(1:3)
for(i in seq_along(x)) {
assign(letters[i], x[i])
}
but usually there is no need for this kind of thing. Why do you want to do that?
Best,
Ista
On Thu, Mar 14, 2013 at 1:17 PM, Sahana Srinivasan
<sahanasrinivasan.91 at gmail.com> wrote:
HI, I'm looking for a function that does the same as deal() in MATLAB, i,e,
for an array x[1 2 3]
[a,b,c]=x;
such that
a=1, b=2, c=3
Does R have any functions similar to this?
[[alternative HTML version deleted]]
______________________________________________ R-help at r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
On Mar 14, 2013, at 12:17 PM, Sahana Srinivasan <sahanasrinivasan.91 at gmail.com> wrote:
HI, I'm looking for a function that does the same as deal() in MATLAB, i,e, for an array x[1 2 3] [a,b,c]=x; such that a=1, b=2, c=3 Does R have any functions similar to this?
There are various R/MATLAB references floating around, one being: http://cran.r-project.org/doc/contrib/Hiebeler-matlabR.pdf A quick search suggests that there is no parallel for 'deal'. In actuality, splitting up an array/vector in this manner would be somewhat "un-R-like", where the general paradigm is to take a "whole object" approach and process/manipulate R objects in their entirety, taking advantage of R's innate vectorized approach to such things. That being said, the ?assign function would take arguments of an R object and a name and assign the object to the name. Since assign() is not vectorized (which is arguably a hint), you would need to use a looping approach, perhaps along these lines: deal <- function(x, Vars) { for (i in seq(along = x)) assign(Vars[i], x[i], envir = parent.frame()) } This will take an object 'x' and assign the value(s) of x to the name(s) contained in 'Vars'. It will assign the value(s) in the calling environment of the function. Thus:
ls()
[1] "deal"
deal(c(1, 2, 3), c("a", "b", "c"))
ls()
[1] "a" "b" "c" "deal"
a
[1] 1
b
[1] 2
c
[1] 3 I did not include any error checking, but you would want to make sure that length(x) == length(Vars) within the function. I would however, urge you to reconsider what you are doing and take advantage of R's philosophy and therefore, strengths. It may be that coercing your source vector to a list would serve you well. Regards, Marc Schwartz
An embedded and charset-unspecified text was scrubbed... Name: not available URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20130314/4e7a54bd/attachment.pl>