R How to Extract Random List Element (Example Code)

In this article, I’ll explain how to pick a random list element in the R programming language.

Construction of Example Data

example_list <- list(10:15,                        # Constructing an example list in R
                     "yalala",
                     6:-3,
                     LETTERS[13:17])
example_list                                       # Showin example list in RStudio console
# [[1]]
# [1] 10 11 12 13 14 15
# 
# [[2]]
# [1] "yalala"
# 
# [[3]]
#  [1]  6  5  4  3  2  1  0 -1 -2 -3
# 
# [[4]]
# [1] "M" "N" "O" "P" "Q"
#

Example: Picking Random Element from List Object

set.seed(289765)                                   # Setting random seed to make example reproducible
list_index <- sample(1:length(example_list), 1)    # Picking list index randomly
example_list[[list_index]]                         # Extracting list element
# [1] "M" "N" "O" "P" "Q"

Further Resources & Related Articles

Have a look at the following R programming tutorials. They illustrate topics such as extracting data, lists, loops, and data elements.

Leave a Reply

Your email address will not be published. Required fields are marked *

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