[R] how to assign a value?

Jinsong Zhao jszhao at yeah.net
Mon Dec 12 03:07:44 CET 2011


On 2011-12-12 0:00, David Winsemius wrote:
>
> On Dec 11, 2011, at 10:27 AM, Jinsong Zhao wrote:
>
>> Hi there,
>>
>> I hope to modify values in a vector or matrix in the following code:
>>
>> for (i in 1:9) {
>> assign(paste("a.", i, sep = ""), 1:i)
>> get(paste("a.", i, sep = ""))[i] <- i+50
>> }
>
> Just one matrix? Then you seem to have inappropriately borrowed using
> "." as an indexing operation. In R that is just another character when
> used as an object name. "a.1" is notgoing to evaulate to a[1]. Look at
> what you would have had after
>
>  > for (i in 1:9) {
> + assign(paste("a.", i, sep = ""), 1:i)
> + }
>  > ls()
> [1] "a" "a.1" "a.2"
> [4] "a.3" "a.4" "a.5"
> [7] "a.6" "a.7" "a.8"
> [10] "a.9"
>
>  > a.1
> [1] 1
>  > a.2
> [1] 1 2
>
> Each of those assign() operations created a single vector of length i. I
> doubt that was what you intended,

yes, it was what I intended.

>
> Better would be to describe your objects and your intentions, rather
> than expecting us to understand your goals by just looking at code that
> doesn't achieve thos goals. (There is no `get<-` function which was the
> source of the error.)
>

The question is why

get(paste("a.", i, sep = ""))[i] <- i+50

give the following error message:

Error in get(paste("a.", i, sep = ""))[i] <- i + 50 :
   target of assignment expands to non-language object

The a.1 to  a.9 was created in the previous step.

if only

get(paste("a.", i, sep = ""))[i]

can give correct output. Why I cannot assign values to it?


Regards,
Jinsong



More information about the R-help mailing list