How to Apply the sample() Function in R (4 Examples)

In this tutorial you’ll learn how to take a simple random sample in the R programming language.

Example 1: Take Subsample of Alphabet

set.seed(951951)                   # Setting seed
sample(LETTERS,                    # Sampling ten letters
       10)
# "N" "Y" "C" "E" "Q" "H" "U" "B" "G" "S"

Example 2: Take Subsample with Replacement

sample(LETTERS,                    # Sampling with replacement
       10,
       replace = TRUE)
# "A" "B" "I" "W" "O" "H" "E" "A" "T" "V"

Example 3: Adjusting Probabilities of Sample Units

sample(LETTERS,                    # Changing sample probabilities
       10,
       replace = TRUE,
       prob = c(75, rep(1, 25)))
# "A" "A" "A" "A" "A" "B" "A" "A" "A" "Q"

Example 4: Subsampling Rows of Data Frame

data(iris)                         # Iris data set
head(iris)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa
iris[sample(1:nrow(iris), 3), ]    # Subsampling rows of data
#     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
# 86           6.0         3.4          4.5         1.6 versicolor
# 123          7.7         2.8          6.7         2.0  virginica
# 35           4.9         3.1          1.5         0.2     setosa

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top