[R] assign a value to an element

David Winsemius dwinsemius at comcast.net
Sun Mar 18 19:50:57 CET 2012


On Mar 18, 2012, at 2:24 PM, Marc Girondot wrote:

> Assign can be used to set a value to a variable that has name as a  
> value of another variable. Example:
>
>> name<-"essai"
>> assign(name, "plouf")
>> essai
> [1] "plouf"
>
> OK.
> But how to do the same when it is only an element of a vector, data  
> frame and so on that must be changed.
>
>> vec<-1:10
>> vec
>  [1]  1  2  3  4  5  6  7  8  9 10
>> vec[4]
> [1] 4
>> name<-"vec[4]"
>> assign(name, 100)
>> vec
>  [1]  1  2  3  4  5  6  7  8  9 10
>
> The reason is probably here (from help of assign):
> assign does not dispatch assignment methods, so it cannot be used to  
> set elements of vectors, names, attributes, etc.

Yes and further, vec[4] in your example does not have a name, since  
you created vect as an unnamed vector. It's not generally optimal  
practice to build up strings and pass them to eval(parse()).

However there is some assignment possible by name to data.frame rows  
with "["

 > vecdf <- data.frame(vec=vec)
 > vecdf['a' , ] <- 20
 > vecdf
   vec
a  20
b  10
c   3
d   4
e   5
f   6
g   7
h   8
i   9
j  10

Where the rowname value is used as the index for assignment. Is that  
sufficiently elegant?

>
> I have found this solution:
>> eval(parse(text=paste(name, "<-100", sep="")))
>> vec
>  [1]   1   2   3 100   5   6   7   8   9  10
>
> Is-it the only way ? It is not very elegant !
>
> Thanks a lot
>
> Marc


David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list