r - 随机化 data.frame 多列中的值
问题描述
我试图随机化多列中的值,但保持行和列的顺序。另外,我只想随机化每列中的值。我基本上想在数据框的多列(不仅仅是V1列)上使用下面的函数。
sample(myDF$V1)
编辑:这是一些带有 dput 的示例数据:
structure(list(V1 = c(9.883752193648, 15.8168998395206, 20.7796219245553,
26.8050975188108), V2 = c(11.8173120437042, 14.1136424787568,
21.4557850824769, 24.5183526363054), V3 = c(10.370627864258,
14.6684224100574, 19.3556715707687, 25.6203798012984), V4 = c(10.520216457555,
16.1207126516696, 18.4468625947703, 25.6121234926508), V5 = c(9.24946800549767,
15.2987236992673, 18.4022904833037, 24.8376890230819)), .Names = c("V1",
"V2", "V3", "V4", "V5"), class = "data.frame", row.names = c(NA,
-4L))
这将是仅 V1 列的结果:
>myDF$V1
9.883752193648, 15.8168998395206, 20.7796219245553, 26.8050975188108
>sample(df1$V1)
26.805098 9.883752 15.816900 20.779622
解决方案
你可能想要这个。使用lapply
适用sample
于每一列。
set.seed(42) # for sake of reproducibility
as.data.frame(lapply(myDF, sample))
# V1 V2 V3 V4 V5
# 1 26.805098 21.45579 19.35567 25.61212 24.837689
# 2 20.779622 14.11364 25.62038 10.52022 9.249468
# 3 9.883752 24.51835 10.37063 18.44686 18.402290
# 4 15.816900 11.81731 14.66842 16.12071 15.298724
编辑
让我们给myDF
行名
rownames(myDF) <- letters[1:4]
我们可以缓冲它们
nm <- rownames(myDF)
并将它们与上面的命令一起返回。
set.seed(42)
myDF <- `rownames<-`(as.data.frame(lapply(myDF, sample)), nm)
myDF
# V1 V2 V3 V4 V5
# a 26.805098 21.45579 19.35567 25.61212 24.837689
# b 20.779622 14.11364 25.62038 10.52022 9.249468
# c 9.883752 24.51835 10.37063 18.44686 18.402290
# d 15.816900 11.81731 14.66842 16.12071 15.298724
数据
myDF <- structure(list(V1 = c(9.883752193648, 15.8168998395206, 20.7796219245553,
26.8050975188108), V2 = c(11.8173120437042, 14.1136424787568,
21.4557850824769, 24.5183526363054), V3 = c(10.370627864258,
14.6684224100574, 19.3556715707687, 25.6203798012984), V4 = c(10.520216457555,
16.1207126516696, 18.4468625947703, 25.6121234926508), V5 = c(9.24946800549767,
15.2987236992673, 18.4022904833037, 24.8376890230819)), class = "data.frame", row.names = c(NA,
-4L))
推荐阅读
- python - 即使连接关闭,Pandas read_sql_query 仍在后台运行?
- laravel - 间接修改重载属性Model没有效果
- postgresql - 即使增加了 work_mem 大小,性能也没有提高
- c++ - C++ ternary assignment of lambda
- ios - 如何在共享扩展的发布操作上显示进度条或加载器
- ruby-on-rails - 找不到资源时如何返回 404,而不是 HTML
- python - 将用户输入与字典和列表进行比较
- html - 如何使用纯 CSS 创建动画表单占位符
- amazon-web-services - 如何在放大中设置 lambda 函数的触发器?
- javascript - 对 jquery 中的 css 函数 @media screen 和 (max-width: 768px) 有任何倡议吗?