How to randomize (or permute) a dataframe rowwise and columnwise?

前端 未结 8 994
Happy的楠姐
Happy的楠姐 2020-11-28 22:50

I have a dataframe (df1) like this.

     f1   f2   f3   f4   f5
d1   1    0    1    1    1  
d2   1    0    0    1    0
d3   0    0    0    1    1
d4   0             


        
8条回答
  •  渐次进展
    2020-11-28 23:27

    Given the R data.frame:

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

    Shuffle row-wise:

    > df2 <- df1[sample(nrow(df1)),]
    > df2
      a b c
    3 0 1 0
    4 0 0 0
    2 1 0 0
    1 1 1 0
    

    By default sample() randomly reorders the elements passed as the first argument. This means that the default size is the size of the passed array. Passing parameter replace=FALSE (the default) to sample(...) ensures that sampling is done without replacement which accomplishes a row wise shuffle.

    Shuffle 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
    

提交回复
热议问题