首页 > 解决方案 > 按列随机化数据表而不丢失属性或更改类型

问题描述

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

ID 高度 重量
一个 54 120
48 200
C 32 250

可能最终看起来像这样:

ID 高度 重量
C 48 250
一个 54 200
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 的每个匹配列匹配?提前致谢。

标签: rattributessample

解决方案


而不是使用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来自collapse(它确实保留了类型和属性)

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

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


推荐阅读