使用for循环匹配和替换

时间:2016-04-22 22:21:44

标签: r matrix

遇到for循环问题。

我试图从每个途径(途径矩阵)中获取元素b b d并将它们与表达数据(表达矩阵)匹配,并将它们放入一个看起来类似于途径矩阵的新矩阵中,但现在包含来自表达矩阵的元素。

我正在努力实现最终的矩阵结果。

a <- c("pathway","1","4","7","pathway-2","1","e","g","pathway-3","4","g","h")
pathway<-matrix(a,3,4, byrow=T)

代码比我希望的措辞更容易理解。

a <- c("pathway","b","c","d","pathway-2","b","e","g","pathway-3","c","g","h")
pathway<-matrix(a,3,4, byrow=T)

b <- c("b",1,"c",4,"d",7)
expression<-matrix(b,3,2, byrow=T)

new<-matrix("a",3,4)
new[1:3,1]<-pathway[,1]

for (x in 1:nrow(expression)){
  for (y in 1:ncol(pathway)){
    if(expression[x,1]==pathway[x,y]){
      new[x,y]<-expression[x,2]
    }
  }
}

1 个答案:

答案 0 :(得分:1)

这是一种方法。我们将pathway[,-1]的每一列与expression[,1]矩阵进行匹配,并将结果矩阵用作expression[,2]值的索引。未找到的返回NA,因此我们将它们编入索引并将其替换为原始矩阵。然后cbind像往常一样获得所需的矩阵。

new_m <- apply(pathway[, -1], 2, function(i) expression[,2][match(i, expression[,1])])
new_m[which(is.na(new_m))] <- pathway[,-1][which(is.na(new_m))]
cbind(pathway[,1], new_m)
#     [,1]        [,2] [,3] [,4]
#[1,] "pathway"   "1"  "4"  "7" 
#[2,] "pathway-2" "1"  "e"  "g" 
#[3,] "pathway-3" "4"  "g"  "h"