【问题标题】:Shuffle Chunks of a Data Frame in RR中数据帧的混洗块
【发布时间】:2021-01-20 20:44:21
【问题描述】:

我有一个 90 行 90 列的数据框。

我的目标是将这个数据框分成 9 块,每块 30 行 30 列。然后,我想随机打乱这 9 个片段以获得一个新的数据帧。

我不确定如何处理这个问题,因为我是 R 的新手。 任何帮助表示赞赏!

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    在向量列表上使用sample,然后取消列表和子集:

    如果我理解正确,您正在尝试做一些类似于 3*3 滑动图片拼图的事情,对吧?您将 df 分成 30 个块,然后“洗牌”这些块。这将做到这一点:

    ### Create a 90 by 90 data frame
    set.seed(2)
    df <- as.data.frame(array(runif(90*90), dim = c(90,90)))
    
    ### Function to randomise subsetting
    rand_dims <- function(){
      myDims <- list(1:30, 31:60, 61:90)
      unlist(sample(myDims))
    }
    
    ### Shuffle 'chunks' of df
    df[rand_dims(), rand_dims()] -> shuffled
    
    ### Checking the leading row/col names
    ### Shows we've succeeded 
    colnames(shuffled)[1:5]
    #> [1] "V61" "V62" "V63" "V64" "V65"
    rownames(shuffled)[1:5]
    #> [1] "31" "32" "33" "34" "35"
    

    由reprex package (v0.3.0) 于 2021-01-21 创建

    【讨论】:

      【解决方案2】:

      也许您可以使用split + sample 尝试以下代码,这有助于对块进行洗牌

      set.seed(1)
      mat <- matrix(data = rnorm(90 * 90), ncol = 90, nrow = 90)
      rrnd <- split(sample(seq(nrow(mat))), gl(3, nrow(mat) / 3))
      crnd <- split(sample(seq(ncol(mat))), gl(3, ncol(mat) / 3))
      
      mat.shuffle <- c()
      for (i in rrnd) {
        for (j in crnd) {
          mat.shuffle <- c(mat.shuffle, list(mat[i, j]))
        }
      }
      

      注意mat.shuffle 是9 块的列表。如果你想转换回大小为90x90的矩阵,你可以在之后运行下面的代码

      out <- do.call(
        rbind,
        lapply(
          split(
            mat.shuffle,
            gl(3, length(mat.shuffle) / 3)
          ),
          function(x) do.call(cbind, x)
        )
      )
      

      你会看到

      > str(out)
       num [1:90, 1:90] -0.639 -0.984 -0.108 -0.939 1.743 ...
      > str(mat.shuffle)
      List of 9
       $ : num [1:30, 1:30] -0.639 -0.984 -0.108 -0.939 1.743 ...
       $ : num [1:30, 1:30] -0.718 -0.154 -0.29 -0.796 1.7 ...
       $ : num [1:30, 1:30] -0.886 0.887 -0.381 0.371 0.327 ...
       $ : num [1:30, 1:30] -0.4555 -0.901 0.0312 -3.0223 0.8688 ...
       $ : num [1:30, 1:30] 0.705 1.559 -1.278 -0.676 1.933 ...
       $ : num [1:30, 1:30] -0.1916 -0.98649 -1.65769 0.00104 -0.19544 ...
       $ : num [1:30, 1:30] 1.668 -0.869 1.469 -0.222 -1.869 ...
       $ : num [1:30, 1:30] 0.9931 0.4116 1.995 -0.4456 -0.0692 ...
       $ : num [1:30, 1:30] -1.462 -0.206 1.197 -1.611 -1.708 ...
      

      【讨论】:

      • 谢谢!这也很有效!
      猜你喜欢
      • 1970-01-01
      • 2023-04-10
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      • 2012-01-25
      • 1970-01-01
      • 2021-02-11
      相关资源
      最近更新 更多