【发布时间】: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