R - Simulate sum of numbers [0-9]

Viewed 47

I am very new to coding in R and wanted some guidance in how to generate this function.

I have a pool of numbers 0 ,1 ,2 ,3 , 4, 5, 6, 7, 8, 9

that I will draw 3 numbers from that pool to sum.

I would like to run this 100 times.

The 3 numbers that I draw from the pool must be unique. i.e 9,9,9 cannot be drawn from the pool.

The current code i have is this.

numbers_in_box <- c(0,1,2,3,4,5,6,7,8,9)
# sample(numbers_in_box,3, replace = FALSE)
replicate(n = 100,sample(numbers_in_box,3, replace = FALSE),simplify = FALSE)

Thank you

3 Answers

The code in the question is not wrong, I would change to simplify = TRUE and start by setting the pseudo-RNG seed. Then assign the output of replicate and colSums to get the sums.

set.seed(2021)    # Make the results reproducible

numbers_in_box <- c(0,1,2,3,4,5,6,7,8,9)
# sample(numbers_in_box,3, replace = FALSE)
x <- replicate(n = 100,sample(numbers_in_box,3, replace = FALSE),simplify = TRUE)

colSums(x)
#  [1] 19 18 15 22 10 11  8 14  8 12 18  8 14 10 13 16 12 12  3 15 12
# [22] 10  6  7 17 21  6 23 17  8  8 10 15 15 15 16 11 11  8  7 18 17
# [43] 18 10  8 12 15 17 16 20 14 14 19 17 11 14 12 14 17 19  7  6 19
# [64]  9 21 19 15 19 18 20 15 13  7 13 21 12 21 16 17 18 20  4 13  8
# [85] 17  8 15 15 15 21 14  8 11 15 17 10 20 18  9  9

Put a sum() call in your replicate():

replicate(n = 100, sum(sample(numbers_in_box,3, replace = FALSE)), simplify = TRUE)

Also, as @Rui suggested, I'd recommend changing simplify to TRUE unless there's some reason you really want a list output rather than a vector.

We can use rerun

library(purrr)
rerun(100, sample(numbers_in_box,3, replace = FALSE))
Related