r语言 - 矩阵索引



我有一个3列56行的矩阵。现在我想对这个矩阵中的每个(I,j)元素执行一个操作,并更新另一个预定义的3列56行矩阵中的值。

我的一小段数据是

miss_geno_probs
[,1]         [,2]         [,3]
[1,] 2.186745e-02 2.936486e-02 9.996548e-03
[2,] 3.131395e-02 4.205017e-02 1.431495e-02
[3,] 3.253137e-02 4.368498e-02 1.487148e-02
[4,] 3.158590e-02 4.241535e-02 1.443927e-02
[5,] 1.240662e-02 1.666031e-02 5.671596e-03
[6,] 3.447492e-02 4.629489e-02 1.575996e-02

我想对每个元素执行一个简单的操作:

w1 <- miss_geno_probs[1,1]/sum(miss_geno_probs[1,])
> w1
[1] 0.3571429

这是我尝试过的,但它不会给我想要的输出:

missing_geno_weights<- matrix(rep(0, length(y_mis) * 3), ncol = 3)
miss_geno_probs<- matrix(rep(0, length(y_mis) * 3), ncol = 3)
for (i in seq_along(marginals)) {
for (j in 0:2){
miss_geno_probs[i,j+1]<- marginals[i] * geno_prop[j+1]
missing_geno_weights[i,j+1]<- miss_geno_probs[i,j+1]/sum(miss_geno_probs[i,])
}
}

再次尝试后,我将其分解为2个for循环,并且第一行的计算是正确的,但仅计算第一行。

missing_geno_weights<- matrix(rep(0, length(marginals) * 3), ncol = 3)
>     for (i in 1:length(marginals)){
for (j in seq_along(1:3)){
missing_geno_weights[i, j]<- miss_geno_probs[i,j]/sum(miss_geno_probs[i,])
}
}
> missing_geno_weights
[,1]      [,2]      [,3]
[1,] 0.3571429 0.4795918 0.1632653
[2,] 0.3571429 0.4795918 0.1632653
[3,] 0.3571429 0.4795918 0.1632653
[4,] 0.3571429 0.4795918 0.1632653
[5,] 0.3571429 0.4795918 0.1632653

你好,我通过重命名矩阵调整了你的代码,但所需的输出是在这里:

INP <- abs(rnorm(9,0,0.09)) # INPUT DATA , an example you replace by your OWN data or your intial matrix 'miss_geno_probs'
INP <- matrix(INP,nrow = 3,ncol = 3) # PUT IN MATRIX  fill in bycol by default
OUT <- matrix(NA,nrow = 3,ncol = 3) # CREATE OUTPUT MATRIX

#PERFORM FOR LOOP
for(row in 1:3){
for(col in 1:3){
OUT[row,col] <- INP[row,col]/sum(INP[,col]) # APPLY DESIRED OPERATION
}
}

相关内容

  • 没有找到相关文章

最新更新