Select Random Element from List in R (Example)

 

In this R tutorial you’ll learn how to pick a random list element.

The post will consist of one example for the random sampling of list items. To be more specific, the content of the post is structured like this:

Let’s jump right to the example:

 

Creation of Example Data

Before all else, we need to create some data that we can use in the examples later on:

my_list <- list("XX",                      # Create example list
                6:3,
                letters[3:5])
my_list                                    # Print example list
# [[1]]
# [1] "XX"
# 
# [[2]]
# [1] 6 5 4 3
# 
# [[3]]
# [1] "c" "d" "e"
#

The previous output of the RStudio console shows the structure of our example data: We have created a list with three list elements.

 

Example: Extract Random List Element Using sample() Function

In this example, I’ll show how to apply the sample function to draw a random list object in R.

It’s good practice to set a random seed first, to make our example reproducible.

set.seed(36958)                            # Set random seed for reproducibility

Next, we can use the sample function to draw a random element from our example list:

my_list[[sample(1:length(my_list), 1)]]    # Pick one list element randomly
# [1] "XX"

The previous R code has randomly picked the list item “XX”.

Please note that the previous R code should only be applied to lists with at least two different list elements. Otherwise, the sample function might not work as expected.

 

Video, Further Resources & Summary

Do you want to know more about drawing at random? Then you may want to have a look at the following video of my YouTube channel. I’m explaining the R programming codes of this tutorial in the video:

 

 

Besides the video, you might want to read the related articles of https://www.statisticsglobe.com/. You can find a selection of tutorials below:

 

Summary: This tutorial has shown how to subset lists randomly in the R programming language. If you have any additional questions, don’t hesitate to let me know in the comments section. Furthermore, don’t forget to subscribe to my email newsletter in order to receive regular updates on new tutorials.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


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.

Top