在每行-R中创建一个带条件求和的矩阵

时间:2014-01-23 22:34:40

标签: r 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

如何使用等于rnorm(18,50,3)的值创建相同的矩阵,但条件是每行的值之和必须小于或等于100.

1 个答案:

答案 0 :(得分:1)

我会做这样的事情

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