在r中使用特定格式提出概率

发布于 2025-01-21 11:27:30 字数 566 浏览 2 评论 0原文

我有这样的数据:

x = c(1,2,3)
prob = c(0.13,0.13,0.74)
# Total sample size
n = 70
result = rep(x, round(n * prob))
Final<-replicate(1, sample(result))

我想制作一个矩阵[7,10],该矩阵的概率为(0.14,0.14,0.72)对于(1,2,3)。在此矩阵中,我需要每七个值1和2重复1,而3次重复5次:

3   3   3   1   2   3   3
3   3   3   3   2   1   3
3   2   1   3   3   3   3
3   3   3   1   3   3   2
2   1   3   3   3   3   3
2   1   3   3   3   3   3
3   3   3   2   1   3   3
3   3   3   3   2   3   1
3   2   1   3   3   3   3

因此,我只能得到一个1,每个RAW中只能得到一个2。您能帮我如何编写代码吗?

I have data like this:

x = c(1,2,3)
prob = c(0.13,0.13,0.74)
# Total sample size
n = 70
result = rep(x, round(n * prob))
Final<-replicate(1, sample(result))

I want to make a matrix[7,10] that have the probability of (0.14,0.14,0.72) for (1,2,3). In this matrix, I need to have in every seven values 1 and 2 repeat 1, and 3 repeats 5 times like this :

3   3   3   1   2   3   3
3   3   3   3   2   1   3
3   2   1   3   3   3   3
3   3   3   1   3   3   2
2   1   3   3   3   3   3
2   1   3   3   3   3   3
3   3   3   2   1   3   3
3   3   3   3   2   3   1
3   2   1   3   3   3   3

So, I will get just one 1, and one 2 in each raw. Could you please help me how to write the code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

中二柚 2025-01-28 11:27:30

一种方法是用3填充矩阵,然后将1和2随机分配到每行的列位置。

set.seed(1)
m <- matrix(rep(3, 7*10), ncol = 7)
pos <- replicate(10, sample(1:7, 2))
for (i in 1:nrow(m)) m[i, pos[,i]] <- 1:2
m
#>       [,1] [,2] [,3] [,4] [,5] [,6] [,7]
#>  [1,]    1    3    3    2    3    3    3
#>  [2,]    2    3    3    3    3    3    1
#>  [3,]    3    1    3    3    2    3    3
#>  [4,]    3    3    2    3    3    3    1
#>  [5,]    3    2    3    3    3    1    3
#>  [6,]    3    3    1    3    3    3    2
#>  [7,]    1    3    3    3    2    3    3
#>  [8,]    3    2    3    3    1    3    3
#>  [9,]    3    3    3    3    3    1    2
#> [10,]    2    1    3    3    3    3    3

One way is to populate a matrix with 3's, then assign 1 and 2 randomly to a column position for each row.

set.seed(1)
m <- matrix(rep(3, 7*10), ncol = 7)
pos <- replicate(10, sample(1:7, 2))
for (i in 1:nrow(m)) m[i, pos[,i]] <- 1:2
m
#>       [,1] [,2] [,3] [,4] [,5] [,6] [,7]
#>  [1,]    1    3    3    2    3    3    3
#>  [2,]    2    3    3    3    3    3    1
#>  [3,]    3    1    3    3    2    3    3
#>  [4,]    3    3    2    3    3    3    1
#>  [5,]    3    2    3    3    3    1    3
#>  [6,]    3    3    1    3    3    3    2
#>  [7,]    1    3    3    3    2    3    3
#>  [8,]    3    2    3    3    1    3    3
#>  [9,]    3    3    3    3    3    1    2
#> [10,]    2    1    3    3    3    3    3

Created on 2022-04-15 by the reprex package (v2.0.1)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文