rayan daou
rayan daou

Reputation: 43

Deeply shuffling a dataframe in R

Im looking for a function or an algorithm to shuffle a dataframe/matrix of floats in R, not by rows or columns only but rather a complete deep randomization of the values.

I tried the function sample() to shuffle the rows first and then the columns but the elements of the same row will end up in the same row just in a different order, im looking more for a complete shuffling.

df =  t1 t2 t3 t3
  g1  1  4   7   0
  g2  8  7  2   9
  g3  4   6   8  1

should result in

df =   t1 t2 t3 t3
  g1  8   2   4   1
  g2  2   1   8   6
  g3  7   9   7   0

Upvotes: 1

Views: 102

Answers (1)

JasonAizkalns
JasonAizkalns

Reputation: 20463

If you use unlist, I believe you can still use sample:

df <- data.frame(
  row.names = c("g1", "g2", "g3"),
  t1 = c(1, 8, 4),
  t2 = c(4, 7, 6),
  t3 = c(7, 2, 8),
  t4 = c(0, 9, 1)
)
df

shuffle <- sample(unlist(df), size = length(unlist(df)))
shuffled_matrix <- matrix(shuffle, nrow = nrow(df), ncol = ncol(df))
df_shuffled <- data.frame(shuffled_matrix)
row.names(df_shuffled) <- row.names(df)
colnames(df_shuffled) <- colnames(df)
df_shuffled

Upvotes: 1

Related Questions