'Simulation with N trials in R

I am trying to create a simulation where a number 0:100 is chosen by a person, then a random number 0:100 is generated using sample(). The difference between their chosen number and the random number is calculated and stored. I would like to use a for loop to run this 10000 times and store the results in a vector so I can later plot the results. Can anyone point me to where I can read about this or see some examples? Below is what I have so far but I keep getting errors saying the lengths aren't the same multiple.

N = 10000
chosen.number = 0:100
generated.number = sample(0:100, N, replace = T)
differences = numeric(0)

for(i in 1:length(chosen.number)){
   differences = (generated.number - chosen.number)
}

Then I'll make a scatterplot of the vector differences.



Solution 1:[1]

Here's an example of how you could go about it (if I understand your questions correctly).

You can set how many loops you want using Repeat.

Since you want a different randomly generated number each time, you'll have to put sample() within your loop. I didn't know where your user-selected number would come from, but in this example, it gets randomly generated with the same set of criteria as the random selection. Then differences are collected in collect_differences for you to use downstream.

Repeat = 10 # Number of times to repeat/loop

collect_differences <- NULL
for(i in 1:Repeat){
  randomly.generated.number = sample(0:100, size = 1, replace = T)
  selected.number = sample(0:100, size = 1, replace = T)
  differences = randomly.generated.number - selected.number

  collect_differences = c(collect_differences, differences)
}
collect_differences

As for resources, you can look up anything related to the fundamentals of looping. You could also look through The Carpentries lessons in R as they have some resources for this as well.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman