【发布时间】:2019-11-14 20:25:18
【问题描述】:
我有一个列表,其中有一个 5x5 矩阵数据集。我想随机选择 2 行,并且在每一行中我想选择 3 个元素,不一定来自相同的列。
所以,我生成了三个数据集并列了一个列表。我能够随机选择 2 行,但很难随机选择 3 个元素而不是选择列。
这是我的代码。
### Generate three data sets
dat1 <- (matrix(rnorm(25), ncol=5))
dat2 <- (matrix(rnorm(25), ncol=5))
dat3 <- (matrix(rnorm(25), ncol=5))
all.dat <- list(dat1=dat1, dat2=dat2, dat3=dat3)
all.dat
#$`dat1`
# [,1] [,2] [,3] [,4] [,5]
#[1,] 1.4394742 0.7064418 -1.3472468 0.52847179 -0.7642337
#[2,] 0.2490570 0.7510308 -0.7028238 -0.09730666 -0.6340773
#[3,] 0.8981850 0.7592610 0.9139721 -0.45700647 -0.2727481
#[4,] -1.0467119 0.2147032 -3.2104254 -0.17797056 0.8897180
#[5,] -0.5437118 0.5803862 -0.1814992 1.93316139 -1.3708932
#$dat2
# [,1] [,2] [,3] [,4] [,5]
#[1,] 1.0442187 -1.4156893 0.5606035101 -1.350030718 0.1538721
#[2,] 0.2080905 -1.7748005 0.8620324724 -0.169071336 -1.7537700
#[3,] 0.9153835 -0.9884572 -1.7279901136 -1.334516414 0.5773021
#[4,] 0.1359423 -1.5107088 -1.4289650078 -0.002001498 -0.4712699
#[5,] 0.1695023 -0.7315209 -0.0003996577 -1.043326258 1.2939485
#$dat3
# [,1] [,2] [,3] [,4] [,5]
#[1,] -1.4994878 -0.59179084 0.998017255 1.4021344 0.5929842
#[2,] 0.3424003 1.33568858 2.214968765 -0.2434351 1.3588000
#[3,] -1.0117892 0.91065720 -0.761932994 -0.8117838 -0.4094731
#[4,] -0.1694781 -0.02937177 -0.826337270 0.2178774 -0.6427046
#[5,] 0.3413101 -0.56911900 0.001363063 0.5579126 -0.9373204
### Select rows and columns.
all.dat.sel.1 <-
lapply(all.dat, function(x) {
x[sample(nrow(x), size = 2), sample(ncol(x), size = 3)]
})
all.dat.sel.1
#$`dat1`
# [,1] [,2] [,3]
#[1,] -0.4570065 0.8981850 -0.2727481
#[2,] 1.9331614 -0.5437118 -1.3708932
#$dat2
# [,1] [,2] [,3]
#[1,] -0.0003996577 -1.043326258 1.2939485
#[2,] -1.4289650078 -0.002001498 -0.4712699
#$dat3
# [,1] [,2] [,3]
#[1,] -1.4994878 1.4021344 0.9980173
#[2,] -0.1694781 0.2178774 -0.8263373
然后,我能够随机选择行,但每行中的元素来自相同的列。例如,第 1 行中的值 -1.4994878 和第 2 行中的 -0.1694781 来自 dat3 中的第 1 列。
我想要的是这样的:
#$dat3
# [,1] [,2] [,3]
#[1,] -1.4994878 0.998017255 0.5929842
#[4,] 0.2178774 -0.02937177 -0.826337270
有一个例子(https://stackoverflow.com/questions/53095050/sample-random-column-for-each-row-in-data-frame)。但是,它适用于数据框而不是列表数据。
【问题讨论】:
-
您想从每个矩阵中抽取 any 2*3 个元素吗?或者结果行元素是否需要来自相同的原始矩阵行?
标签: r list random lapply sample