

When you set replace=TRUE, we are basically simulating a situation where we choose a card, write down the number, and then put it back before picking up another card. You will notice that we have chose some numbers multiple times (“2” appears three times, “10” and “6” appear twice). But you cannot shuffle 11 cards out of a deck of 10.Ĭompare this to the case when we set replace=TRUE: set.seed(2) In the first iteration, you have simply shuffled the order of the numbers. Sample(1:10, 10, replace=F) #10 random numbers between 1 and 10 # 2 7 5 10 6 8 1 3 4 9īut this will NOT work: sample(1:10, 11, replace=F) #11 random numbers between 1 and 10 # Error in sample.int(length(x), size, replace, prob): cannot take a sample larger than the population when 'replace = FALSE' We can do that up to the sample size, but no more. This is akin to physically picking 5 cards out of a set of 10 at the same time. Note that we have used replace=F to indicate that, once we choose a number, we want to avoid choosing it again. Try changing the number inside the set.seed() and see what you get.
#Random number loop in r code
When you run the code like this, you should always get “2, 7, 5, 10, 6” Sample(1:10, 5, replace=F) #5 random numbers between 1 and 10s # 2 7 5 10 6 What we can do is to use set.seed() to make this process repeatable: set.seed(2) #you can put whatever number inside set.seed() This makes sense, but it makes it difficult to make this code reproducible. You will probably notice that you have generated a different set of random numbers than what is shown here. sample(1:10, 5, replace=F) #5 random numbers between 1 and 10 # 10 5 8 1 2 For example, let’s sample 5 integer between 1 and 10. Say, for example, we want to sample randomly from a set of numbers. We often want to generate a set of random number given some distribution. 9.1.1 Sampling from a given set of numbers with or without replacement.
