2011-03-22 44 views
1

我創建了一個類似下面的循環來檢查與表中的行匹配的條件。如果它們匹配,則打印出rowname。如果它們不匹配,則不會發生任何事情。將表的多行匹配到多個條件

condition <- c(0,0,1,1) 
id <- apply(table, 1, 
      function(i) sum(i[1:length(table)] != condition)==0) 
idd<-as.matrix(id) 
for (i in 1:length(idd)){      
    if (idd[i] == TRUE) { 
     print(rownames(idd)[i]) 
    }    
} 

> table         
>   [1] [2] [3] [4]      
>1651838 1 1 0 0 
>1653006 0 0 0 0 
>1656415 0 0 0 1 
>1657317 -1 0 0 0 

我的問題是:是否有可能使這個循環的多個條件?例如:

condition <- c("0,0,0,0","0,0,0,1","0,0,1,0","0,1,0,0","1,0,0,0", 
       "0,0,1,1","1,1,0,0","0,1,1,0","1,0,0,1","1,0,1,0", 
       "0,1,0,1","1,0,1,1","1,1,0,1","1,1,1,0","0,1,1,1","1,1,1,1") 

for(r in 1:length(condition)){ 
    id <- apply(regulationtable, 1, 
       function(i) sum(i[1:length(regulationtable)] != condition[r])==0 
       ) 
    idd<-as.matrix(id) 
    test<-list() 
    for (i in 1:length(idd)) {      
     if (idd[i] == TRUE) { 
      print(rownames(idd)[i]) 
     }    
     test[[i]]<-matrix(idtest) 
    } 
} 

謝謝!

+1

看起來非常相似的措詞http://stackoverflow.com/questions/5375642/venndiagram-create-list-of-venncounts – 2011-03-22 10:26:37

回答

1

如何:

## make up data 
z <- matrix(c(1,0,0,-1,1, 
       1,0,0,0,1, 
       0,0,0,0,0, 
       0,0,1,0,0), 
      nrow=5, 
      dimnames=list(LETTERS[1:5],NULL)) 

condition <- c("0,0,0,0","0,0,0,1","0,0,1,0","0,1,0,0","1,0,0,0", 
       "0,0,1,1","1,1,0,0","0,1,1,0","1,0,0,1","1,0,1,0", 
       "0,1,0,1","1,0,1,1","1,1,0,1","1,1,1,0","0,1,1,1","1,1,1,1") 

strtab <- apply(z,1,paste,collapse=",") 
## rownames(z)[match(condition,strtab)] ## first match only 
omat <- outer(condition,strtab,"==") ## all comparisons 
colnames(omat)[col(omat)][omat]  ## select corresponding colnames 

+0

這是一個真正的解決方案,但如果Z有兩個相同的行,只顯示第一行。 – Lisann 2011-03-22 15:11:30

+0

會爲您修改版本嗎? (PS:我不知道你是否可以改變你的問題的標題,但它看起來不是很具描述性:我會說「像表中的多行匹配多個條件」 - 正確的答案需要不涉及循環,實際上可能不會... – 2011-03-22 19:19:30

2

在二元%函數%應該返回匹配的所有行:

> rownames(table)[strtab %in% condition] 
[1] "1651838" "1653006" "1656415" 

> tabl2 <- table[c(1:4, 3), ] 
> rownames(tabl2)[strtab %in% condition] 
[1] "1651838" "1653006" "1656415" "1656415" 

(我有點驚訝地聽到,比賽不會那麼做,因爲在%%的在用寫比賽它的核心。)

+0

你是對的,這是我需要的,謝謝! – Lisann 2011-03-23 11:10:37

+0

比我的好... – 2011-03-23 13:21:31