[R] Equivalent of deal in R?

Marc Schwartz marc_schwartz at me.com
Thu Mar 14 18:56:09 CET 2013


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



More information about the R-help mailing list