[R] Use of the index of a for loop to assign values to the rows of a series of variables

Thomas Lumley tlumley at u.washington.edu
Wed Mar 22 16:33:12 CET 2006


On Wed, 22 Mar 2006, Domenico Vistocco wrote:

> Dear All,
> It is difficult to summarize the question in few words. So, please,
> look at the following example.
> Thanks in advance,
> domenico
>
> ----------------------------------------------------------------------------------------------------------------------------------------------------------
> rm(list = ls())
> posfix=1:5* 10
> for(i in posfix)
> 	assign(paste("matX.",i,sep=""),matrix(0,3,2))
> ls()
>
> [1] "i"       "matX.10" "matX.20" "matX.30" "matX.40" "matX.50" "posfix"
> AT THIS STEP I HAVE 5 MATRIX OF ZEROS (3 ROWS PER 2 COLUMNS)
> NOW I WOULD LIKE TO ASSIGN TO A ROW OF THE  5 MATRICES A VALUE
> RELATED TO THE INDEX OF A FOR LOOP

Don't do that. Make matX a list of matrices, so that matX.10 is matX[[1]], 
matX.20 is matX[[2]].

> for(i in 1:length(posfix))
> 	assign(paste("matX.",posfix[i],"[",i,",]",sep=""),i)
> ls()
>
>  [1] "i"           "matX.10"     "matX.10[1,]" "matX.20"     "matX.20[2,]"
>  [6] "matX.30"     "matX.30[3,]" "matX.40"     "matX.40[4,]" "matX.50"
> [11] "matX.50[5,]" "posfix"
>
> ??????????????????
> WHY IT DOES NOT ASSIGN THE VALUE TO THE ROWS OF THE PRE-INITIALIZED
> VARIABLES. WHERE IS MY ERROR?

The help page for assign says
     'assign' does not dispatch assignment methods, so it cannot be
      used to set elements of vectors, names, attributes, etc.

There is a solution using eval and substitute, but you really don't want 
to go there.

 	-thomas




More information about the R-help mailing list