[R] assigning a new variable to multiple data frames

Gabor Grothendieck ggrothendieck at gmail.com
Sat Dec 6 22:33:30 CET 2008


Viewing ?assign we see that the first two arguments to assign are required
but in the example shown in the question there is only one argument.

Also ?assign says the first argument is "a variable name, given as a
character string"
which is not the case in the code in the question.

Also as a matter of course its not a good idea to use c as a variable name even
though R can usually determine that you did not mean the function c (although
sometimes it can't).

C <- matrix(1:100, 10)
cc <- matrix(1:50, 10)

for(m in c("C", "cc")) assign(m, cbind(get(m), new = 9))

Depending on your intention you may prefer to have C and cc be list
components.  That would significantly simplify iteration over them. In
that case c could be a name since names of list components cannot
be confused with functions:

L <- list(c = matrix(1:100, 10), cc = matrix(1:50, 10))
L <- lapply(L, cbind, new = 9)

On Sat, Dec 6, 2008 at 4:09 PM, Georg Ehret <georgehret at gmail.com> wrote:
> Dear R community,
>   I am trying to assign a new variable (named "new") to multiple dataframes
> by a loop and do not succeed... Can you please help?
> Thank you and best regards, Georg Ehret.
>
>> c
>   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
> 1   1 11 21 31 41 51 61 71 81  91
> 2   2 12 22 32 42 52 62 72 82  92
> 3   3 13 23 33 43 53 63 73 83  93
> 4   4 14 24 34 44 54 64 74 84  94
> 5   5 15 25 35 45 55 65 75 85  95
> 6   6 16 26 36 46 56 66 76 86  96
> 7   7 17 27 37 47 57 67 77 87  97
> 8   8 18 28 38 48 58 68 78 88  98
> 9   9 19 29 39 49 59 69 79 89  99
> 10 10 20 30 40 50 60 70 80 90 100
>> cc
>   V1 V2 V3 V4 V5
> 1   1 11 21 31 41
> 2   2 12 22 32 42
> 3   3 13 23 33 43
> 4   4 14 24 34 44
> 5   5 15 25 35 45
> 6   6 16 26 36 46
> 7   7 17 27 37 47
> 8   8 18 28 38 48
> 9   9 19 29 39 49
> 10 10 20 30 40 50
>> names<-c("c","cc")
>> for(i in names){assign(get(i))$new<-rep(9,10)}
> Error in assign(`*tmp*`) :
>  element 2 is empty;
>   the part of the args list of '.Internal' being evaluated was:
>   (x, value, envir, inherits)
> ****************************
> Georg Ehret
> Geneva University Hospital
> Switzerland
>
>        [[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.
>



More information about the R-help mailing list