如果......在for循环中

时间:2017-03-12 10:42:58

标签: r if-statement for-loop matrix

我正在编写一个函数来对二进制矩阵的每一行执行位反转,这取决于预定义的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's函数执行以下操作:

  1. 如果所选行的n小于difference,则随机选择几个索引(0)并反转它们。 (11's
  2. 否则,如果所选行的数量n大于difference,则随机选择几个索引(1)并反转它们。 (01's
  3. 否则不执行任何操作(当行的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) } 时。)
  4. 以下是我实施的功能:

    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 (单行矩阵)时,该函数似乎工作正常。

    结果:

    for

    我的if...else>>> print http.codemap[404] 'Not found' 循环中是否有错误?

1 个答案:

答案 0 :(得分:2)

更改“j”中的循环

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
}
相关问题