Home > Mobile >  Make a probability with specific format in R
Make a probability with specific format in R

Time:04-15

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?

CodePudding user response:

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)

  • Related