简体   繁体   English

R,rbinom(),NA和矩阵:如何忽略NA却保留它们

[英]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. 问题是我需要在矩阵中保留一些NA值,但是输入NA时rbinom()返回错误。

My algorithm consists of the following: 我的算法包括以下内容:

  • (1) start with a matrix of values in one column. (1)从一列值矩阵开始。
  • (2) double the values in that matrix. (2)将矩阵中的值加倍。
  • (3) select a random value from a binomial probability of 0.5. (3)从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(). 我不知道如何将矩阵重新组合在一起,因为我需要从xn_bin中获取结果,并将其放回新矩阵中的相同位置,因为dup值已输入rbinom()中。

If that does not make any sense. 如果那没有任何意义。 xn_bin will give the values: xn_bin [1] 101 115 112 98 103 103 xn_bin将给出值:xn_bin [1] 10111511298103103

dup will give: dup将给出:

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: 我希望最终矩阵具有xn_bin的值和xn的NA值:

         [,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): 请注意,顺序不同,但是矩阵结构中的位置是所需的,并且由于这是一个随机过程,不应由位置确定,因此我不明白为什么此结果不如您的排序有效(已填充R个矩阵)按列而不是按行):

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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