问题描述
如何从填充有1和0的矩阵中抽取n个随机点的样本?
How can I take a sample of n random points from a matrix populated with 1's and 0's ?
a=rep(0:1,5)
b=rep(0,10)
c=rep(1,10)
dataset=matrix(cbind(a,b,c),nrow=10,ncol=3)
dataset
[,1] [,2] [,3]
[1,] 0 0 1
[2,] 1 0 1
[3,] 0 0 1
[4,] 1 0 1
[5,] 0 0 1
[6,] 1 0 1
[7,] 0 0 1
[8,] 1 0 1
[9,] 0 0 1
[10,] 1 0 1
我想确定我抽取N个样本时的位置(行,列)是随机的.
I want to be sure that the positions(row,col) from were I take the N samples are random.
我知道sample {base}
,但是它似乎不允许我这样做,我知道的其他方法是空间方法,它们将迫使我添加x,y并将其更改为空间对象,然后再次返回到法线矩阵.
I know sample {base}
but it doesn't seem to allow me to do that, other methods I know are spatial methods that will force me to add x,y and change it to a spatial object and again back to a normal matrix.
更多信息
More information
我是随机地说,它也散布在矩阵空间"内,例如如果我不希望得到4个相邻点,而我又希望得到4个相邻点,则我希望它们在矩阵空间"中传播.
By random I mean also spread inside the "matrix space", e.g. if I make a sampling of 4 points I don't want to have as a result 4 neighboring points, I want them spread in the "matrix space".
知道我取出随机点的矩阵中的位置(行,列)也很重要.
Knowing the position(row,col) in the matrix where I took out the random points would also be important.
推荐答案
如果您了解R在内部将矩阵表示为向量,则有一种非常简单的方法可以对矩阵进行采样.
There is a very easy way to sample a matrix that works if you understand that R represents a matrix internally as a vector.
这意味着您可以直接在矩阵上使用sample
.例如,假设您要对10个要替换的点进行采样:
This means you can use sample
directly on your matrix. For example, let's assume you want to sample 10 points with replacement:
n <- 10
replace=TRUE
现在只需在矩阵上使用sample
:
Now just use sample
on your matrix:
set.seed(1)
sample(dataset, n, replace=replace)
[1] 1 0 0 1 0 1 1 0 0 1
为演示其工作原理,让我们将其分解为两个步骤.第1步是生成采样位置的索引,第2步是在矩阵中找到这些位置:
To demonstrate how this works, let's decompose it into two steps. Step 1 is to generate an index of sampling positions, and step 2 is to find those positions in your matrix:
set.seed(1)
mysample <- sample(length(dataset), n, replace=replace)
mysample
[1] 8 12 18 28 7 27 29 20 19 2
dataset[mysample]
[1] 1 0 0 1 0 1 1 0 0 1
而且,请记住,这两种方法的结果是相同的.
And, hey presto, the results of the two methods are identical.
这篇关于随机抽样-矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!