Randomly shuffling Multiple columns
This approach is almost similar to the previous approach. The only difference here is we are using sample() function on multiple columns, this randomly shuffles those columns. We have called the sample function on columns c2 and c3, due to these columns, c2 and c3 are shuffled.
Syntax:
data.frame(c1=df$c1, c2=sample(df$c2), c3=sample(df$c2))
Example: R program to randomly shuffle contents of a column
R
df <- data.frame(c1=c("a1", "b2", "c3", "d4"),
c2=c("w1", "x2", "y3", "z4"),
c3=c("1a", "2b", "3c", "4d"))
df_shuffled=data.frame(c1=df$c1, c2=sample(df$c2), c3=sample(df$c2))
df_shuffled
Output:
c1 c2 c3 1 a1 w1 x2 2 b2 y3 z4 3 c3 x2 w1 4 d4 z4 y3
How to randomly shuffle contents of a single column in R dataframe?
In this article, we will learn how can we randomly shuffle the contents of a single column using R programming language.
Sample dataframe in use:
c1 | c2 | c3 |
---|---|---|
a1 | w1 | 1a |
b2 | x2 | 2b |
c3 | y3 | 3c |
d4 | z4 | 4d |