【问题标题】:Randomize datatable by column without losing attributes or changing type按列随机化数据表而不丢失属性或更改类型
【发布时间】:2021-07-16 23:48:29
【问题描述】:

我的目标是按列随机化数据表中的值序列,而不会丢失与每列关联的属性。每列应独立于其他列随机化。所以一个看起来像这样的数据集:

ID height weight
A 54 120
B 48 200
C 32 250

可能最终看起来像这样:

ID height weight
C 48 250
A 54 200
B 32 120

可复制的例子:

library(tidyverse)
library(labelled)

dat<-data.table(a=c(1,2,3,4,5),
                b=c("one","two","three","four","five"),
                c=c(10,9,8,7,6))

var_label(dat$a)<-"The a variable"
var_label(dat$b)<-"The b variable"
var_label(dat$c)<-"The c variable"

val_label(dat$a,1)<-"First option"
val_label(dat$a,2)<-"Second option"
val_label(dat$a,3)<-"Third option"
val_label(dat$a,4)<-"Fourth option"
val_label(dat$a,5)<-"Fifth option"

new_dat<-as.data.table(apply(dat,2,sample))

问题是这样的:

str(dat$a)
 dbl+lbl [1:5] 1, 2, 3, 4, 5
 @ labels: Named num [1:5] 1 2 3 4 5
  ..- attr(*, "names")= chr [1:5] "First option" "Second option" "Third option" "Fourth option" ...
 @ label : chr "The a variable"

str(new_dat$a)
 chr [1:5] "2" "3" "5" "4" "1"

我有一个中等大小的数据集(约 10,000 行和约 250 列),我需要复制它,所以我真的不想要一个随机的解决方案。有没有办法做到这一点,不涉及询问 dat 的每一列的结构并强制 new_dat 的每个匹配列匹配?提前致谢。

【问题讨论】:

    标签: r attributes sample


    【解决方案1】:

    而不是使用apply(转换为matrix,矩阵只能有一个类)。使用lapply

    newdat <- copy(dat)
    newdat[] <- lapply(newdat, sample)
    

    -检查结构

    str(newdat)
    #Classes ‘data.table’ and 'data.frame': 5 obs. of  3 variables:
    # $ a: dbl+lbl [1:5] 2, 3, 4, 5, 1
    #   ..@ labels: Named num  1 2 3 4 5
    #   .. ..- attr(*, "names")= chr [1:5] "First option" "Second option" "Third option" "Fourth option" ...
    #   ..@ label : chr "The a variable"
    # $ b: chr  "five" "three" "two" "one" ...
    # $ c: num  6 10 8 7 9
    

    或者另一个快速的选择是dapply from collapse(它确实保留了类型和属性)

    library(collapse)
    newdat <- dapply(newdat, sample)
    

    如果数据集有多个类型(在不同的列中),实际上永远不要使用apply

    【讨论】:

    • 太棒了。首先感谢您提供有效的答案,然后再提供更好的答案。
    猜你喜欢
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 2011-07-25
    • 1970-01-01
    • 2014-08-15
    • 2017-12-07
    • 1970-01-01
    相关资源
    最近更新 更多