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

Liaw, Andy andy_liaw at merck.com
Wed Mar 22 16:39:29 CET 2006


1. The matrices are only 3x2.  In your loop you'd be assigning rows 4 and 5
in the last two iterations.  Are you sure that's what you want?

2. The reason it ``didn't work'' is because assign() takes the first
argument as the name of the object to create, literally, instead of
evaluating it.

3. You probably ought to be working with a list.  E.g.:

m <- replicate(5, matrix(0, 5, 2), simplify=FALSE)
names(m) <- paste("MAT", 1:5 * 10, sep="")
for (i in 1:length(m)) m[[i]][i, ] <- i

Andy

ps:  Please try not to use all caps:  It's the equivalent of shouting on top
of your lungs.  Not exactly the thing to do when you're asking for help.


From: Domenico Vistocco
> 
> 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
> 
> 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?
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list 
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
> 
>




More information about the R-help mailing list