Create a matrix with notional sum on each row -R

I created this matrix:

> atr <- matrix(rnorm(18,50,3), nrow=9, ncol=2) 
> atr
      [,1] [,2]
 [1,] 49.1 46.3
 [2,] 49.9 49.2
 [3,] 52.3 51.6
 [4,] 49.3 46.1
 [5,] 54.3 51.8
 [6,] 46.7 47.2
 [7,] 46.6 57.6
 [8,] 53.9 53.4
 [9,] 46.6 53.1

      

How do I create the same matrix with values ​​equal to rnorm (18,50,3), but with the condition that the sum of the values ​​for each row must be less than or equal to 100.

0


source to share


1 answer


I would do something like this



nrow <- 9
ncol <- 2
mat <- matrix(nrow = nrow, ncol = ncol)
i <- 1
while (i <= nrow) {
    x <- rnorm(ncol, mean = 50, sd = 3)
    if (sum(x) <= 100) {
        mat[i, ] <- x
        i <- i + 1
    }
}

      

+1


source







All Articles