【问题标题】:Deeply shuffling a dataframe in R在 R 中深度洗牌数据框
【发布时间】:2019-07-06 13:06:29
【问题描述】:

我正在寻找一个函数或算法来对 R 中的浮点数据帧/矩阵进行洗牌,而不是仅按行或列,而是对值进行完全深度随机化。

我尝试使用 sample() 函数先对行进行洗牌,然后再对列进行洗牌,但同一行的元素最终会以不同的顺序出现在同一行中,我正在寻找更多的完整洗牌。

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

应该会导致

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

【问题讨论】:

    标签: r dataframe random shuffle


    【解决方案1】:

    如果你用unlist,相信你还是可以用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
    

    【讨论】:

      猜你喜欢
      • 2021-04-23
      • 2019-05-25
      • 2018-04-01
      • 1970-01-01
      • 2016-04-29
      • 2017-08-10
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      相关资源
      最近更新 更多