Question

In this answer: https://stackoverflow.com/a/11503439/651779 it is shown how to shuffle a dataframe row- and column wise. I am interested in shuffeling column wise. From the original dataframe

> df1
  a b c
1 1 1 0
2 1 0 0
3 0 1 0
4 0 0 0

shuffling column wise

> df3=df1[,sample(ncol(df1))]
> df3
  c a b
1 0 1 1
2 0 1 0
3 0 0 1
4 0 0 0

However, I would like to shuffle each row on its columns independent of the other rows, instead of shuffling the complete columns, so that you could get something like

>df4
  c a b
1 0 1 1
2 1 0 0
3 1 0 0
4 0 0 0

Now I do that by looping over each row, shuffling the row, and putting it in a dataframe. Is there an easy way to do this?

Was it helpful?

Solution

something like:

t(apply(df1, 1, function(x) { sample(x, length(x)) } ))

This will give you the result in matrix form. If you have factors, a mix of numeric and characters etc, be aware that this will coerce everything to character.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top