2016-04-03 52 views
1

我想不出這裏發生了什麼(R語言):超簡易R for循環不工作

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¿什麼想法?

提前致謝!

+0

你能告訴你的預期輸出使用which功能和length的總數? – akrun

回答

2

我們可以做到這一點沒有任何環

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 

如果上面的輸出是預計,隨着for一層的方法是將初始化「B」與length等於「樣品的ncol '然後通過列的順序循環‘空間’

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 

注:在OP的代碼for LO op是j in ncol(space),它的長度是1,而不是循環遍歷序列。


如果我們想去的地方都值是1或兩者都是0

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

或者使用table

tbl <- table(combn(a, 2, FUN = sum)) 
tbl[names(tbl)!=1] 

# 0 2 
#10 6 

使用OP的代碼列數(改爲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 

但是,假設我們做

b <- 0 
for(j in 1:ncol(space)){ 
    if(space[1, j] == 1 & space[2,j]==1){ 
    b = b + 1 
    } 
    } 
b 
#[1] 6 
+0

非常感謝,但爲什麼我自己的循環不起作用?任何想法?謝謝! – MarioMadrid

+0

@MarioMadrid更新爲'for'循環代碼。如果這樣做,請考慮通過點擊投票旁邊的勾號來接受解決方案。 – akrun

+0

再次感謝,但上面的輸出不是我所期望的,只是想獲得矩陣「空間」的列數,其中兩行都取值1或兩行都取值爲0. – MarioMadrid

1

可以在各種條件

# 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