问题描述
我需要生成具有不同样本量的多项式随机变量.
I need to genereate multinomial random variables with varying sample size.
假设我已经按如下方式生成了我的样本大小,
Let say i already generated my sample sizes as follows,
samplesize =c(50,45,40,48)
然后我需要根据这个不同的样本大小生成多项式随机变量.我尝试使用 for 循环并使用应用函数(sapply).
then i need to generate multinomial random variables based on this varying sample size. I tried this using a for loop and using a apply function(sapply).
使用 For 循环,
p1=c(0.4,0.3,0.3)
for( i in 1:4)
{
xx1[i]=rmultinom(4, samplesize[i], p1)
}
如果我的代码是正确的,那么我应该得到一个有 4 列和 3 行的矩阵.其中列总数应等于样本大小中的每个值.但我不明白.
If my code is correct then i should get a matrix that have 4 columns and 3 rows. Where column totals should equal to the each value in sample sizes. But i am not getting that.
使用 Sapply ,
Using Sapply ,
sapply( samplesize ,function(x)
{
rmultinom(10, samplesize[x], p1)
})
我也在这里遇到错误.
那么任何人都可以帮我弄清楚出了什么问题吗?
So can any one help me to figure out what went wrong ?
谢谢
推荐答案
samplesize <- c(50, 45, 40, 48)
p <- c(0.4, 0.3, 0.3)
## method 1
set.seed(0)
xx1 <- matrix(0, length(p), length(samplesize))
for(i in 1:length(samplesize)) {
xx1[, i] <- rmultinom(1, samplesize[i], p)
}
xx1
# [,1] [,2] [,3] [,4]
#[1,] 24 17 20 24
#[2,] 11 14 8 16
#[3,] 15 14 12 8
colSums(xx1)
#[1] 50 45 40 48
## method 2
set.seed(0)
xx2 <- sapply(samplesize, rmultinom, n = 1, prob = p)
xx2
# [,1] [,2] [,3] [,4]
#[1,] 24 17 20 24
#[2,] 11 14 8 16
#[3,] 15 14 12 8
colSums(xx2)
#[1] 50 45 40 48
注意:rmultinom
不像其他分布函数那样矢量化"说 rnorm
>.
Note: rmultinom
is not "vectorized" like other distribution functions say rnorm
.
set.seed(0)
fail <- rmultinom(length(samplesize), samplesize, p)
# [,1] [,2] [,3] [,4]
#[1,] 24 19 25 24
#[2,] 11 16 10 17
#[3,] 15 15 15 9
colSums(fail)
#[1] 50 50 50 50
所以R级for
循环或sapply
循环或使用糖函数Vectorize
是必要的.
So the R-level for
loop or sapply
loop or using sugar function Vectorize
is necessary.
这篇关于在 R 中生成具有不同样本大小的多项随机变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!