将表的多行匹配到多个条件

时间:2011-03-22 09:37:36

标签: r loops

我创建了一个如下所示的循环来检查与表中的行匹配的条件。如果匹配,则打印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)
    }
}

谢谢!

2 个答案:

答案 0 :(得分:2)

%dyadic函数中的%应返回匹配的所有行:

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

(听到这场比赛不会那样,我有点惊讶,因为%in%是以匹配为核心。)

答案 1 :(得分: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