Skip to content

assign

6 messages · Perez Martin, Agustin, PIKAL Petr, Peter Wolf +3 more

#
DeaR useRs:

I would like to assign a values in an object using a loop 'for'.
This is a reduce example of my problem, my real problem is a few
complicated:

for (j in 1:10) {
	x.j<-rnorm(100)
}

I want to create 10 objects as "x.1, x.2, ... , x.9, x.10" with values in
it.
I used the "assign" function but nothing happens.
Thank you very much
#
Hi

is it possible for you to use one object (data frame) and assign 
along its collumns?
x x x x x x
 [1,] 0 0 0 0 0 0
 [2,] 0 0 0 0 0 0
 [3,] 0 0 0 0 0 0
 [4,] 0 0 0 0 0 0
 [5,] 0 0 0 0 0 0
 [6,] 0 0 0 0 0 0
 [7,] 0 0 0 0 0 0
 [8,] 0 0 0 0 0 0
 [9,] 0 0 0 0 0 0
[10,] 0 0 0 0 0 0
or you can use list in quite similar manner.

Cheers
Petr
On 7 Jan 2004 at 17:53, Perez Martin, Agustin wrote:

            
Petr Pikal
petr.pikal at precheza.cz
#
Perez Martin, Agustin wrote:

            
Use eval or assign:

 > for(j in 1:10) eval(parse(text=paste("x",j,"<-",j,sep="")))
 > x1
[1] 1
 > x8
[1] 8
 > for(j in 1:10) eval(parse(text=paste("x",j,"<-rnorm(10)",sep="")))
 > x1
 [1]  0.49045324  0.44842510 -1.18015351 -0.04325187 -0.75345939 -0.99181309
 [7]  0.62517301 -0.68466635  0.33383560 -0.62189500
 > x2
 [1] -0.4344948  2.0276137  1.2783173  1.1170551  0.3546490 -0.0748969
 [7] -0.8817247 -1.4649175 -1.5461995 -0.6575016
 > for(j in 1:10) assign(paste("y",j,sep=""),rnorm(10))
 > y1
 [1] 1.7255925 0.4993323 1.8846513 0.2058971 0.2284036  -3.1971553
 [7]  -0.2629365 0.2724788  -0.9911388  -0.6341857
 > y2
 [1] 0.11301503  -1.28497666 0.40670853 0.08479014 1.05818411  -1.10843908
 [7] 1.30441911  -0.49050833  -1.21438645 0.03923849
ls()
 [1] "j"   "x1"  "x10" "x2"  "x3"  "x4"  "x5"  "x6"  "x7"  "x8"  "x9"  "y1"
[13] "y10" "y2"  "y3"  "y4"  "y5"  "y6"  "y7"  "y8"  "y9"

pw
#
On Wed, 7 Jan 2004, Perez Martin, Agustin wrote:

            
Actually, you assigned ten times to object x.j. As was mentioned earlier 
today in reference to a different question, you will almost always find 
that what you think you need and what works best are not the same - a list 
here would be much more convenient:

x <- vector(mode="list", length=10)
for (j in 1:10) {
  x[[j]] <- rnorm(100)
}

for example. For more complicated list elements, the arguments for using 
lists are even stronger. Take a little time to make lists your friends, 
they are powerful and flexible.

  
    
#
Use assign().

varnames <- paste("x", 1:10, sep = ".")
for(j in 1:10) {
	assign(varnames[j], rnorm(10))
}

-roger
Perez Martin, Agustin wrote: