[英]How to find sample for different sample size for different probability
我有兩個 3x3 矩陣,P 和 Q。P 是概率矩陣。 我想根據 P 中不同樣本大小的概率在 Q 中找到隨機樣本。
例如,我想根據 P[1,] 在 Q[1,] 中找到大小為 10 的樣本,根據 P[2,] 在 Q[2,] 中找到大小為 6 的樣本,在 Q 中找到大小為 3 的樣本[3,] 基於 P[3,]
這是我的代碼:
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)}
我嘗試運行代碼,這是我的結果,這是錯誤的,因為樣本沒有從相應的行中選擇,詳細來說,第一個結果中可以選擇的值只能是 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
誰能幫我找出代碼中的問題,並幫助我解決這個問題? 非常感謝 !
您應該只需要一個循環。 嘗試 -
#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.