简体   繁体   中英

How to find sample for different sample size for different probability

I have two 3x3 matrices, P and Q. P is probability matrix. I want to find random sample in Q based on the probability in P for different sample size.

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,]

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.

[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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM