lundi 28 novembre 2022

How to shuffle data frame entries in R

I have a data frame with dimension 24,523x3,468 and I want to shuffle the entries of this dataframe. For example, I have a simple data frame

df <- data.frame(c1=c(1, 1.5, 2, 4), c2=c(1.1, 1.6, 3, 3.2), c3=c(2.1, 2.4, 1.4, 1.7)) 
df_shuffled = transform(df, c2 = sample(c2))

It works for one column, but I want to shuffle all column, or all rows. I tried

col = colnames(df)
for (i in 1:ncol(df)){
  df2 = transform(df, col[i] = sample(col[i]))
}
df2

It will produce an error like this

error

I have tried this too to shuffle, but it only shuffles rows and columns

df_shuf = df[sample(rownames(df), nrow(df)), sample(colnames(df), ncol(df))]
df_shuf

shuffle

How can I shuffle the entries of the data frame df using a loop for I by rows and columns?




Aucun commentaire:

Enregistrer un commentaire