[英]How to find sample for different sample size for different probability
I have two 3x3 matrices, P and Q. P is probability matrix.我有两个 3x3 矩阵,P 和 Q。P 是概率矩阵。 I want to find random sample in Q based on the probability in P for different sample size.我想根据 P 中不同样本大小的概率在 Q 中找到随机样本。
For example, I want to find sample of size 10 in Q[1,] based on P[1,] , sample of size 6 in Q[2,] based on P[2,] , and sample of size 3 in Q[3,] based on P[3,]例如,我想根据 P[1,] 在 Q[1,] 中找到大小为 10 的样本,根据 P[2,] 在 Q[2,] 中找到大小为 6 的样本,在 Q 中找到大小为 3 的样本[3,] 基于 P[3,]
Here is my code:这是我的代码:
P=matrix(c(0.5,0.3,0.2,0.7,0.2,0.1,0,0.2,0.8),ncol=3,nrow=3,byrow=T)
Q=matrix(c(50,100,150,0,4,200,0,10,600),ncol=3,nrow=3,byrow=T)
samplesize=c(10,6,3)
for(i in samplesize){
for(x in 1:3){
p=P[x,]
s=sample(Q[x,],size=i,p=p,replace=T)}
print(s)}
I tried to run the code and here is my result which is wrong because the sample is not chosen from the corresponding row , to be detailed, the value can be chosen in first result can only be 50,100 and 150,600 should not be chosen.我尝试运行代码,这是我的结果,这是错误的,因为样本没有从相应的行中选择,详细来说,第一个结果中可以选择的值只能是 50,100,不应选择 150,600。
[1] 10 600 600 600 600 600 600 600 600 600
[1] 600 10 600 600 600 600
[1] 600 600 600
May anyone help me to figure out the problem in my code, and help me with that?谁能帮我找出代码中的问题,并帮助我解决这个问题? thankyou very much !非常感谢 !
You should need only one loop.您应该只需要一个循环。 Try -尝试 -
#To store the result
result <- vector('list', length(samplesize))
for(i in seq_along(samplesize)){
#get value from i'th row in Q,
#probability from i'th row in P
#and sample size from i'th value in samplesize
result[[i]] = sample(Q[i,],size=samplesize[i],p=P[i, ],replace=T)
}
result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.