[R] loop in R
Michael Bedward
michael.bedward at gmail.com
Wed Oct 6 12:10:47 CEST 2010
Hello Julia,
Your loop is just "overwriting" your variables each time.
Is this the sort of thing you want ?
# make a matrix with 10 cols of N random uniform values
N <- 5
x <- t( replicate( 10, runif(N, 0, 1) ) )
You can leave out the t( ... ) part if you want the randomizations to
be rows instead of cols
Michael
On 6 October 2010 20:51, Julia Lira <julia.lira at hotmail.co.uk> wrote:
>
> 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
>
>
>
> 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))
> u <- c(u1,u2,u3,u4,u5)
> mu <- matrix(u, nrow=1000, ncol=1)
> }
>
>
> 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