Reputation: 1981
I would like to have a vector res
with length 200, which includes 20 times repetition of random generation values divided by 2 which is r[i]
, how can I get this in R?I wrote the following code but it is just save each iteration values,not the whole iterations.
r = rep(0, 10)
res = matrix(0, nrow=200, ncol=1)
for(j in 1:20){
for(i in 1:10){
x = rnorm(10, 0, 1)
r[i] = x/2
}
res = rbind(r)
}
Upvotes: 0
Views: 70
Reputation: 605
as Roland said in a comment to your question writing two loops for this isn't a good practice. However, you can do it like this
res = rep(0, 200)
r = rep(0, 10)
for(j in 1:20){
for(i in 1:10){
x = rnorm(1, 0, 1)
r[i] = x/2
}
res[((j-1)*10+1):(j*10)] = r
}
As for your solution, there were some problems:
res = matrix(0, nrow=200, ncol=1)
if you only need a vectorrnorm(10,0,1)
returns a vector of 10 values so assigning it to r[i]
(which takes only one value) isn't correctrbind
is used to connect two vectors/matrices/... by rows so using it with only one parameter doesn't really make a sense hereUpvotes: 2