R: Simulation


I. Discrete Simulation
In R, one can use the sample function to simulate random events. 

II. Examples
A basketball player makes 30% of the free-throws attempted. Using R, simulate 40 free throws, then construct a table of made vs. missed shots.
> # USE SAMPLE FUNCTION TO SIMULATE FREE THROWS
> shots = sample(x = c("made", "missed"), 
+                size = 40, 
+                replace = TRUE, 
+                prob = c(0.3, 0.7))
> shots
 [1] "missed" "made"   "made"   "missed" "missed" "missed" "made"   "missed" "missed" "missed" "made"  
[12] "made"   "missed" "missed" "missed" "missed" "missed" "missed" "missed" "made"   "made"   "made"  
[23] "missed" "missed" "missed" "made"   "missed" "missed" "missed" "missed" "missed" "made"   "made"  
[34] "missed" "made"   "made"   "missed" "missed" "missed" "missed"
> 
> table(shots)
shots
  made missed 
    13     27 

 

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.