将data.frame的多个列中的值随机化

时间:2019-03-26 18:01:48

标签: r loops random shuffle sample

我正在尝试将多列中的值随机化,但要保留行和列的顺序。另外,我只想随机化每一列中的值。我基本上想在数据框的多列(不只是V1列)上使用下面的函数。

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))

编辑:这是一些带有dput的示例数据:

>myDF$V1
9.883752193648, 15.8168998395206, 20.7796219245553, 26.8050975188108

>sample(df1$V1)
26.805098  9.883752 15.816900 20.779622

这里只是V1列的结果:

imul esi, esi, 0x0A

1 个答案:

答案 0 :(得分:1)

您可能想要这个。使用lapplysample应用于每一列。

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))