Perform the following steps to understand data sampling in R:
- To generate random samples of a given population, the user can simply use the sample function:
> sample(1:10)
- To specify the number of items returned, the user can set the assigned value to the size argument:
> sample(1:10, size = 5)
- Moreover, the sample can also generate Bernoulli trials by specifying replace = TRUE (default is FALSE):
> sample(c(0,1), 10, replace = TRUE)
- If we want to do a coin flipping trail, where the outcome is Head or Tail, we can use:
> outcome <- c("Head","Tail") > sample(outcome, size=1)
- To generate result for 100 times, we can use:
> sample(outcome, size=100, replace=TRUE)
- The sample can be useful when we want to select random data from datasets, selecting 10 observations from AirPassengers:
> sample(AirPassengers, size=10)