0
votes

I am experimenting with R and would like to implement a loop which runs 1000000 times and creates a vector of length 10 and adds each vector to a data frame under the name cycle and the number it has iterated.

This is my current code:

loser <- 100
winner <- 500
percentageWinner <- 70
runns <- 1000000
numbs <- 10
for(i in runns ) {
  randNumb <- runif(numbs, min=0, max=100)
  outcome <- ifelse(randNumb < percentageWinner, winner, loser) # true are winners and false are losers
  df <- data.frame(outcome)
  colnames(df)[which(names(df) == "outcome")] <- paste("cycle",i)

}
df 

I am struggeling to add the vector next to the other data.frame column.

Any suggestions, how to do that?

I appreciate your replies!

1
At each iteration of your for loop, you overwrite i by 1 (i <- 1). And if you remove it, i will be always equal to runns, i.e only 1 loop. - user3710546
@Pascal Yep true. Changed my sample code. - Carol.Kar

1 Answers

3
votes

In your code, at each iteration of your for loop, you overwrite i by 1 (i <- 1). And if you remove it, it will be always equal to runns, i.e only 1 loop.

You need to change your code for something like:

loser <- 100
winner <- 500
percentageWinner <- 70
runns <- 1000000
numbs <- 10
outcome <- matrix(NA, numbs, runns)
for(i in seq_len(runns)) {
  randNumb <- runif(numbs, min=0, max=100)
  outcome[,i] <- ifelse(randNumb < percentageWinner, winner, loser)
}
df <- data.frame(outcome)
colnames(df) <- paste0("cycle",seq_len(runns))

Or you can avoid the loop:

randNumb <- runif(numbs*runns, min=0, max=100)
outcome <- ifelse(randNumb < percentageWinner, winner, loser)
outcome <- matrix(outcome, numbs, runns)
df <- data.frame(outcome)
colnames(df) <- paste0("cycle",seq_len(runns))