Skip to content

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:
#
On Mar 14, 2013, at 12:17 PM, Sahana Srinivasan <sahanasrinivasan.91 at gmail.com> wrote:

            
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:
[1] "deal"

deal(c(1, 2, 3), c("a", "b", "c"))
[1] "a"    "b"    "c"    "deal"
[1] 1
[1] 2
[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