【问题标题】:If...else within a for loopif...else 在 for 循环中
【发布时间】:2017-08-02 10:50:38
【问题描述】:

我正在编写一个函数来为二进制矩阵的每一行执行位反转,这取决于预定义的n 值。 n 值将确定矩阵每一行的1 位数。

set.seed(123)
## generate a random 5 by 10 binary matrix
init <- t(replicate(5, {i <- sample(3:6, 1); sample(c(rep(1, i), rep(0, 10 - i)))}))
n <- 3
## init_1 is a used to explain my problem (single row matrix)
init_1 <- t(replicate(1, {i <- sample(3:6, 1); sample(c(rep(1, i), rep(0, 10 - i)))}))

bit_inversion 函数做了以下几件事:

  1. 如果所选行的1's 数小于n,则随机选择几个索引(difference)并反转它们。 (01
  2. 否则,如果所选行的1's 数量大于n,则随机选择几个索引(difference)并反转它们。 (10
  3. 否则什么都不做(当行中1's 的数量等于n。)

下面是我实现的功能:

bit_inversion<- function(pop){

        for(i in 1:nrow(pop)){ 
                difference <- abs(sum(pop[i,]) - n)
                ## checking condition where there are more bits being turned on than n
                if(sum(pop[i,]) > n){
                        ## determine position of 1's
                        bit_position_1 <- sample(which(pop[i,]==1), difference)
                        ## bit inversion
                        for(j in 1:length(bit_position_1)){
                                pop[bit_position_1[j]] <- abs(pop[i,][bit_position_1[j]] - 1)

                        } 
                } 

                else if (sum(pop[i,]) < n){
                        ## determine position of 0's
                        bit_position_0 <- sample(which(pop[i,]==0), difference)
                        ## bit inversion
                        for(j in 1:length(bit_position_0)){
                                pop[bit_position_0[j]] <- abs(pop[bit_position_0[j]] - 1)

                        }
                }
        }

        return(pop)
}

结果:

call <- bit_inversion(init)
> rowSums(call)  ## suppose to be all 3
 [1] 3 4 5 4 3

但是当使用init_1(单行矩阵)时,该函数似乎工作正常。

结果:

call_1 <- bit_inversion(init_1)
> rowSums(call)
[1] 3

我的forif...else 循环中有错误吗?

【问题讨论】:

  • 这是用于生成 0/1 矩阵的可怕代码。试试这个:nr &lt;- 5; nc &lt;- 10; init &lt;- matrix(rbinom(nr*nc, 1, 0.5), nrow=nr, ncol=nc)

标签: r if-statement for-loop matrix


【解决方案1】:

改变'j' for 循环中的行

pop[bit_position_1[j]] <- abs(pop[i,][bit_position_1[j]] - 1)

进入

pop[i,bit_position_1[j]] <- abs(pop[i,][bit_position_1[j]] - 1)

您忘记了行索引。

而且,这里有一个更紧凑的 for 循环版本:

for(i in 1:nrow(pop)){
  difference <- abs(sum(pop[i,]) - n)
  logi <- sum(pop[i,]) > n
  pop[i,sample(which(pop[i,]==logi), difference)] <- !logi
}

【讨论】:

    猜你喜欢
    • 2019-12-04
    • 2012-11-13
    • 1970-01-01
    • 2021-09-16
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多