开发者

matching multiple rows of a table to multiple conditions

I created a loop lik开发者_开发百科e below to check in the condition matched with the rows in table. If they match, the rowname is printed. if they don't match, nothing is happend.

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

my question is: is it possible to make this loop for multiple conditions? something like:

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)
    }
}

Thanks!


The %in% dyadic function should return all rows that match:

> 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"

(I'm a bit surprised to hear that match wouldn't do that, since %in% is written with match at its core.)


How about:

## 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜