1

I will try to be as clear as possible. Imagine you have a for cycle, that results in a vector. Now you would like to rerun the for cycle, and thus create another vector with different values in it. The problem is, you would like to keep the first one while getting a new one. Basically you would want series of vectors like vector1 from the first run, vector2 from the second run... Is it possible to write a cycle that would allow this? Also, would it be possible to create a matrix that combines these vectors in a way that every single vector is stored as a row?

Thank you in advance!

  • This is all possible and easy... see, e.g., `?replicate`. If you need more help than a pointer like that, you'll need to read up on the Stack Overflow guidance, like [How to create a minimal, complete, verifiable example](http://stackoverflow.com/help/mcve). Also reading the R-specific [How to create a reproducible example in R](http://stackoverflow.com/q/5963269/903061) and following that advice will help your question get positive attention. – Gregor Thomas Jan 09 '17 at 23:20

1 Answers1

1

Not sure I fully understand the ask but does this work?

# Function to assign values using a for loop
forCycle <- function(x){
  # create an empty vector
  v <- c()
  for(i in 1:10){
    v[i] <- i * x
  }
  return(v)
}

# create an empty data frame with 10 rows
df <- data.frame(x=rep(0, 10))

for(y in 1:3){
  df[,y] <- forCycle(y)
}

Your will end up with a dataframe like this:

    x V2 V3
1   1  2  3
2   2  4  6
3   3  6  9
4   4  8 12
5   5 10 15
6   6 12 18
7   7 14 21
8   8 16 24
9   9 18 27
10 10 20 30
PhilC
  • 767
  • 3
  • 8