超简单的R for循环不工作

时间:2016-04-03 10:53:16

标签: r for-loop

我无法弄清楚这里发生了什么(R语言):

a = c(1, 1, 1, 1, 0, 0, 0, 0, 0)
space = combn(a,2)
b = 0
for(j in ncol(space)){
 if(space[1, j] == space[2, j]){
   b = b + 1
    }
 }

我得到b = 1,这不应该是1.¿任何想法?

提前致谢!

2 个答案:

答案 0 :(得分:2)

我们可以在没有任何循环的情况下完成此操作

instance GetEndpoint (Verb n s ct a) (Verb n s ct a) 'True where
  getEndpoint _ _ _ _ server = server

如果上述输出是预期的,combn(a, 2, FUN = function(x) +(x[1]==x[2])) #[1] 1 1 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 循环的一种方法是初始化' b' for等于length'样本'然后在'空间'

中循环遍历列的序列
ncol

注意:在OP的代码中,b <- numeric(ncol(space)) for(j in 1:ncol(space)){ if(space[1, j] == space[2, j]){ b[j] = b[j] + 1 } } b #[1] 1 1 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 循环为for,长度为1而不是循环序列。

如果我们想要两个值都是1或两者都是0的列数

j in ncol(space)

或使用sum(colSums(space)==2) #[1] 6 sum(!colSums(space)) #[1] 10

table

使用OP的代码(更改为 tbl <- table(combn(a, 2, FUN = sum)) tbl[names(tbl)!=1] # 0 2 #10 6

1:ncol(space)

但是,假设我们做了

 b <- 0
 for(j in 1:ncol(space)){
   #Note that here we are not differentiating whether both 
   #are 0 or both are 1
   if(space[1, j] == space[2, j]){
     b = b + 1
      }
    }
 b
 #[1] 16

答案 1 :(得分:1)

您可以使用which函数和length作为每种情况下的总计数

# Both the rows having value 1
> which(space[1,] == 1 & space[2,] == 1) 
[1]  1  2  3  9 10 16
# Both the rows having value 0
> which(space[1,] == 0 & space[2,] == 0) 
[1] 27 28 29 30 31 32 33 34 35 36
# Row 1 having value 1 and row 2 having value 0
> which(space[1,] == 1 & space[2,] == 0) 
[1]  4  5  6  7  8 11 12 13 14 15 17 18 19 20 21 22 23 24 25 26
# ROw 1 having value 0 and row 2 having value 1
> which(space[1,] == 0 & space[2,] == 1)
integer(0)

# Total number obtained from each case above:
> length(which(space[1,] == 1 & space[2,] == 1))
[1] 6

> length(which(space[1,] == 0 & space[2,] == 0))
[1] 10

> length(which(space[1,] == 1 & space[2,] == 0))
[1] 20

> length(which(space[1,] == 0 & space[2,] == 1))
[1] 0