[R] Odp: loop in R

Petr PIKAL petr.pikal at precheza.cz
Wed Oct 6 12:11:24 CEST 2010


Hi

r-help-bounces at r-project.org napsal dne 06.10.2010 11:51:37:

> 
> Dear all,
> 
> 
> 
> I need to do a loop in R, but I am not sure the software is generating 
"n" 
> times the variables I request differently. When I ask to print the last 
matrix
> created, I just can see the loop for n=1.
> 
> To be more precise, supose I need to simulate 10 times one variable and 
I want
> to fit the 10 variables simulated in a matrix. I dont really know what I 
am 
> doing wrong, but I just can see 1 variable created.
> 
> Below follows an example of what I want:
> 
> 
> 
> rm(list=ls()) #remove almost everything in the memory

Not in memory but in file .Rdata on your PC too when you end your session

> 
> 
> 
> set.seed(180185)
> 
> 
> 
> #loop: create 10 times the variables (u1,u2,u3,u4,u5)
> 
> 
> 
> for (i in 1:10){
> u1 <- c(runif(200,0,1))
> u2 <- c(runif(200,0,1))
> u3 <- c(runif(200,0,1))
> u4 <- c(runif(200,0,1))
> u5 <- c(runif(200,0,1))

Five vectors with 200 numbers each despite of excessive c() construction.

> u <- c(u1,u2,u3,u4,u5)

vector of length 1000

> mu <- matrix(u, nrow=1000, ncol=1)

changed to matrix

> }

all made 10 times. Imagine you do a loop

for (i i 10) {
copy "file1" to "file2"
}

what do you expect as a result? Ten files or only one file? When you want 
a matrix with 10 colums and 1000 rows you can set it before your loop

mu <- matrix(NA, nrow=1000, ncol=10)
and use

mu[,i] <- u 
as the last row in your loop. But what is wrong with

mu <- matrix(runif(10000, 0,1), nrow=1000, ncol=10)

for getting such matrix.

Regards
Petr

> 
> 
> As you can see, when I print(mu), I just can see a matrix with the 
vector u in
> one column. I also tried to increase the number of columns to 10 (or i), 
but 
> the matrix will have 10 times the same vector. And what I need is like a 
Monte
> Carlo simulation, where I have to simulate 10 times the variables above.
> 
> 
> 
> Am I doing something wrong?
> 
> 
> 
> Thanks in advance!
> 
> 
> 
> Julia 
> 
>    [[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list