我正在编写一个函数来对二进制矩阵的每一行执行位反转,这取决于预定义的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
函数执行以下操作:
n
小于difference
,则随机选择几个索引(0
)并反转它们。 (1
至1's
)n
大于difference
,则随机选择几个索引(1
)并反转它们。 (0
至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
(单行矩阵)时,该函数似乎工作正常。
结果:
for
我的if...else
和>>> print http.codemap[404]
'Not found'
循环中是否有错误?
答案 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
}