How to Generate a Sample Using the Sample Function in R?
In this article, we will discuss how to generate a sample using the sample function in R.
Sample() function is used to generate the random elements from the given data with or without replacement.
sample(data, size, replace = FALSE, prob = NULL)
- data can be a vector or a dataframe
- size represents the size of the sample
- replace is used to set the values again repeated if it is set to true
- prob: a vector of probability weights for obtaining the elements of the vector being sampled
Example 1: Generate sample data from the vector
Here, we will generate the n sample data from the given vector with 11 elements using the sample function.
 45 7 5 34  3  5 23 8 21 6 45
Example 2: Generate sample data from the vector by replacing
Here we are going to create a vector with 11 elements and generate the sample data with a replacement.
 45 5 5 3  86  5 5 8 7 8 45
Example 3: Sampling with Uneven Probabilities Using sample Function
Here we are going to select the elements with higher probability than others by setting the probability using the prob parameter.
 23 23 23 23 23 45 23 23 23 23
Example 4: Random Sampling of Data Frame Rows Using sample Function
Here we are going to sample the dataframe, let us create a dataframe and sample the rows.
Example 5: Random Sampling of List Elements Using sample Function
Here we are going to sample the data in the list with size 4
[]  2 []  1 []  4 []  6