Create a matrix with conditional sum in each row -R

梦想与她 提交于 2020-01-25 11:35:50

问题


I've 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 Can I create the same matrix with values equal to rnorm(18,50,3) but with the condition that the sum of values on each row must be less or equal than 100.


回答1:


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
    }
}


来源:https://stackoverflow.com/questions/21320753/create-a-matrix-with-conditional-sum-in-each-row-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!