0

(As an exercise) I was trying to emulate some languages such as perl, etc by assigning to multiple variables in R.

my ($a, $b, $c) = ( 1, 2, 3 );

now $a is 1, $b is 2, $c is 3.

I expected this to work:

mapply(assign, c('A', 'B', 'C'), 1:3)

But it just returned a named int vector of 1,2,3.

Why didn't this work as expected?

Edit: First part of my question was indeed a duplicate of: Assign multiple new variables on LHS in a single line in R but would still like to know why my approach of mapply/assign didn't work.

Community
  • 1
  • 1
  • 1
    `mapply` doesn't work because it will always collect the results into a single object. (and the assignment is by default taking place in the current environment, not the global one) – joran May 30 '14 at 16:52
  • ...for instance, `mapply(assign, x = c('A', 'B', 'C'), value = 1:3,MoreArgs = list(envir = .GlobalEnv))` would have worked, but will also return the single object you saw before. – joran May 30 '14 at 16:58
  • The "why" part of your question is also answered at the duplicate, as several of those answers use the same assign/mapply strategy as you, the only difference being that they took care to specify the correct environment for the assignment. I added the comments above in order to be sure that that was clear. – joran May 30 '14 at 17:27
  • Ah...thanks! I missed your comments on this question, apologies. – distracted-biologist May 30 '14 at 17:32

0 Answers0