问题
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