r - 按列随机化数据表而不丢失属性或更改类型
问题描述
我的目标是按列随机化数据表中的值序列,而不会丢失与每列关联的属性。每列应独立于其他列随机化。所以一个看起来像这样的数据集:
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 的每个匹配列匹配?提前致谢。
解决方案
而不是使用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
如果数据集有多个类型(在不同的列中),则实际上永远不会使用。
推荐阅读
- java - 无法在 Java 应用程序中实现 DAO 设计模式
- python-3.x - 是否可以“自定义”python?
- dictionary - Ansible 构建字典列表并附加到字典中的列表
- reactjs - setState 到嵌套对象删除值
- javascript - 如何切换 React 列表中的按钮?
- swiftui - Image view 如何在 SWiftUI 中通过 URL 显示照片?
- javascript - Safari — 在前几个之后无法创建振荡器
- java - 调用 response.getStatus 时响应为 NULL,客户端不是针对 web 服务中的内容吗?
- c++ - 友元非成员函数出错,导致分段错误
- amazon-web-services - 如何在我的新 CloudFormation 模板中引用现有角色?