How to Shuffle a Data Frame Rowwise & Columnwise in R (2 Examples)

In this article you’ll learn how to shuffle the rows and columns of a data frame randomly in the R programming language.

Example Data

data(iris)                                   # Load data set
head(iris)                                   # Head of data
#   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

Example 1: Randomly Reorder Data Frame Rowwise

set.seed(873246)                             # Setting seed
iris_row <- iris[sample(1:nrow(iris)), ]     # Randomly reorder rows
head(iris_row)                               # Print head of new data
#     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
# 118          7.7         3.8          6.7         2.2  virginica
# 9            4.4         2.9          1.4         0.2     setosa
# 70           5.6         2.5          3.9         1.1 versicolor
# 65           5.6         2.9          3.6         1.3 versicolor
# 101          6.3         3.3          6.0         2.5  virginica
# 91           5.5         2.6          4.4         1.2 versicolor

Example 2: Randomly Reorder Data Frame Columnwise

set.seed(84636)                              # Setting seed
iris_col <- iris[ , sample(1:ncol(iris))]    # Randomly reorder columns
head(iris_col)                               # Print head of new data
#   Petal.Length Petal.Width Species Sepal.Width Sepal.Length
# 1          1.4         0.2  setosa         3.5          5.1
# 2          1.4         0.2  setosa         3.0          4.9
# 3          1.3         0.2  setosa         3.2          4.7
# 4          1.5         0.2  setosa         3.1          4.6
# 5          1.4         0.2  setosa         3.6          5.0
# 6          1.7         0.4  setosa         3.9          5.4

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