malasi
malasi

Reputation: 61

Store values from a loop

I am simulating dice throws, and would like to save the output in a single object, but cannot find a way to do so. I tried looking here, here, and here, but they do not seem to answer my question.

Here is my attempt to assign the result of a 20 x 3 trial to an object:

set.seed(1) 
Twenty = for(i in 1:20){   
  trials = sample.int(6, 3, replace = TRUE)   
  print(trials)   
  i = i+1 
}
print(Twenty)

What I do not understand is why I cannot recall the function after it is run?

I also tried using return instead of print in the function:

Twenty = for(i in 1:20){
  trials = sample.int(6, 3, replace = TRUE)
  return(trials)
  i = i+1
}
print(Twenty)

or creating an empty matrix first:

mat = matrix(0, nrow = 20, ncol = 3)
mat    
for(i in 1:20){
  mat[i] = sample.int(6, 3, replace = TRUE)
  print(mat)
  i = i+1
}

but they seem to be worse (as I do not even get to see the trials).

Thanks for any hints.

Upvotes: 1

Views: 102

Answers (3)

Slug Pue
Slug Pue

Reputation: 256

There are several things wrong with your attempts:

1) A loop is not a function nor an object in R, so it doesn't make sense to assign a loop to a variable

2) When you have a loop for(i in 1:20), the loop will increment i so it doesn't make sense to add i = i + 1.

Your last attempt implemented correctly would look like this:

mat <- matrix(0, nrow = 20, ncol = 3)
for(i in 1:20){
     mat[i, ] = sample.int(6, 3, replace = TRUE)
}
print(mat)

I personally would simply do

matrix(sample.int(6, 20 * 3, replace = TRUE), nrow = 20)

(since all draws are independent and with replacement, it doesn't matter if you make 3 draws 20 times or simply 60 draws)

Upvotes: 1

Parfait
Parfait

Reputation: 107642

Usually, in most programming languages one does not assign objects to for loops as they are not formally function objects. One uses loops to interact iteratively on existing objects. However, R maintains the apply family that saves iterative outputs to objects in same length as inputs.

Consider lapply (list apply) for list output or sapply (simplified apply) for matrix output:

# LIST OUTPUT
Twenty <- lapply(1:20, function(x) sample.int(6, 3, replace = TRUE))

# MATRIX OUTPUT
Twenty <- sapply(1:20, function(x) sample.int(6, 3, replace = TRUE))

And to see your trials, simply print out the object

print(Twenty)

But since you never use the iterator variable, x, consider replicate (wrapper to sapply which by one argument can output a matrix or a list) that receives size and expression (no sequence inputs or functions) arguments:

# MATRIX OUTPUT (DEFAULT)
Twenty <- replicate(20, sample.int(6, 3, replace = TRUE))

# LIST OUTPUT
Twenty <- replicate(20, sample.int(6, 3, replace = TRUE), simplify = FALSE)

Upvotes: 1

Jim Chen
Jim Chen

Reputation: 3729

You can use list:

Twenty=list()
for(i in 1:20){
  Twenty[[i]] = sample.int(6, 3, replace = TRUE)
}

Upvotes: 0

Related Questions