user21478
user21478

Reputation: 155

Updating Values in R

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?

Upvotes: 1

Views: 209

Answers (3)

milan
milan

Reputation: 4970

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)
}

Upvotes: 1

lmo
lmo

Reputation: 38500

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

Upvotes: 1

Matias Thayer
Matias Thayer

Reputation: 621

one way you can do it:

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

Upvotes: 2

Related Questions