1

Suppose I have the following code:

 x <- vector(mode="numeric", length=10)
 for(i in 1:10)
    {
       x[i] <- runif(1,0,10)
    }

So x has 10 values. In each of the next steps, I want to add 10 new values to x . So in step 2, x would have 20 values, in step 3 it would have 30 values etc. How would I do this?

Tim Assal
  • 677
  • 6
  • 15
user21478
  • 155
  • 2
  • 3
  • 10
  • 1
    Possible duplicate of [Append value to empty vector in R?](http://stackoverflow.com/questions/22235809/append-value-to-empty-vector-in-r) – cdeterman Jun 13 '16 at 16:03
  • 2
    Any particular reason for using a loop? `runif` is vectorized and can give you all these values at once. – Roland Jun 13 '16 at 16:23

3 Answers3

2

one way you can do it:

x <- vector(mode="numeric")
for(i in 1:10)
{
  x<-c(x, runif(10,0,10))
}
Matias Thayer
  • 571
  • 3
  • 8
1

One possibility is to use a matrix:

x <- matrix(0, 10, 10)

Then fill in the columns:

for(i in 1:10) {
  x[, i] <- runif(1,0,10)
}

If you really want a vector at the end:

x <- as.numeric(x)

or you can accomplish this by removing the dimensions attribute:

dim(x) <- NULL
lmo
  • 37,904
  • 9
  • 56
  • 69
1

You can just create an additional 'for loop'. Use the first for (i in 1:2) to tell how many additional vectors of 10 values you need.

x <- x2 <- NULL
for (i in 1:2){
for(i in 1:10)
{
x[i] <- runif(1,0,10)
}
x2 <- c(x2, x)
}
milan
  • 4,782
  • 2
  • 21
  • 39