简体   繁体   中英

R, rbinom(), NA, and matrices: How to ignore NA yet retain them

I am putting some values in a matrix through a binomial probability expression. The problem is that I have some NA values that I need to keep in my matrix, but rbinom() returns an error when NA is inputted.

My algorithm consists of the following:

  • (1) start with a matrix of values in one column.
  • (2) double the values in that matrix.
  • (3) select a random value from a binomial probability of 0.5.
  • ... some more things that are uneccessary

Here is a reproducible example.

set.seed(10)
xn <- matrix(c(NA, 100, 100, 100, 100, NA, NA, 100, 100, NA), byrow=TRUE, ncol=2)
dup <- xn * 2 
z <- matrix(rbinom(n=rep(1,length(dup)), size = as.vector(dup), prob = 0.5), nrow = nrow(dup))
Warning message:
In rbinom(n = rep(1, length(dup)), size = as.vector(dup), prob = 0.5) :
  NAs produced

I thought about only selecting the values in the matrix that have actual values.

set.seed(6)
xn_bin <- rbinom(n=rep(1,length(dup[-which(is.na(dup))])), size = as.vector(dup[-which(is.na(dup))]),prob = 0.5)

I don't know how to get the matrix back together since I need take the results from xn_bin and put them back into the same position in a new matrix as the dup values were located inputted into rbinom().

If that does not make any sense. xn_bin will give the values: xn_bin [1] 101 115 112 98 103 103

dup will give:

dup
     [,1] [,2]
[1,]   NA  200
[2,]  200  200
[3,]  200   NA
[4,]   NA  200
[5,]  200   NA

I want the final matrix to have the values from xn_bin and the NA values from xn:

         [,1] [,2]
[1,]   NA   101
[2,]   115  112
[3,]   98   NA
[4,]   NA   103
[5,]   103  NA

Any idea how to do this effectively?

Notice that the order is not the same but position in the matrix structure is as desired and since this is a random process that should not be determined by positon I do not see why this result is not as valid as your ordering (R matrices being filled by column rather than by row):

 xn_bin <- z

 set.seed(6)
 xn_bin[ !is.na(z) ] <- rbinom(n=rep(1,length(dup[-which(is.na(dup))])), 
                               size = as.vector(dup[-which(is.na(dup))]),prob = 0.5)
 xn_bin
     [,1] [,2]
[1,]  NaN   98
[2,]  101  103
[3,]  115  NaN
[4,]  NaN  103
[5,]  112  NaN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM