Randomize Vector in R (Example) | Shuffle & Mix Elements Randomly

 

In this R programming tutorial you’ll learn how to shuffle a vector or array randomly.

The content is structured as follows:

Let’s dive right into the R code.

 

Creation of Example Data

Have a look at the following example data:

x <- 1:10                  # Example vector
x                          # Print vector
# 1  2  3  4  5  6  7  8  9 10

Have a look at the previously shown RStudio console output. It shows that our example data is a simple numeric vector ranging from 1 to 10.

 

Example: Randomly Mix Vector Using sample() Function

This Section explains how to shuffle our numeric vector randomly using the sample function.

First, we are setting a seed for reproducibility. Then, we are applying the sample function to create a new data object called x_rand. This data object contains our randomly mixed vector.

set.seed(872436)           # Set seed
x_rand <- sample(x)        # Sample vector
x_rand                     # Print shuffled vector
# 6  1  3 10  9  7  5  8  2  4

The previous RStudio console output shows the result: A randomly permuted array.

 

Video, Further Resources & Summary

Do you need further information on the examples of this post? Then I can recommend to have a look at the following video of my YouTube channel. I illustrate the R codes of the present tutorial in the video:

 

 

Besides that, you might have a look at the other tutorials of www.statisticsglobe.com:

 

In this article, I explained how to mix the ordering of vector elements in the R programming language. Please let me know in the comments section, if you have further questions. Furthermore, don’t forget to subscribe to my email newsletter to get updates on the newest 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