【发布时间】: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'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 循环中有错误吗?
【问题讨论】:
-
这是用于生成 0/1 矩阵的可怕代码。试试这个:
nr <- 5; nc <- 10; init <- matrix(rbinom(nr*nc, 1, 0.5), nrow=nr, ncol=nc)
标签: r if-statement for-loop matrix