I have a simple for-loop for pattern matching and and getting the values from another matrix. It is bit slow to run for large number of rows. I am trying to convert it into a function and then using apply. But I am not getting the same result as the for loop. Can someone tell me what am I doing wrong. Thanks
Here is the for loop:
exp_target_com = structure(list(X06...2239_normal = c(12.2528814946075,  8.25298920937508), X06...2239_tumor = c(12.476021286337, 6.08504757235585), Ensembl_Id = structure(c(NA_integer_, 
NA_integer_), .Label = "", class = "factor"), HGNC = structure(c(NA_integer_, 
NA_integer_), .Label = "", class = "factor")), .Names = c("X06...2239_normal", "X06...2239_tumor", "Ensembl_Id", "HGNC"), class = "data.frame", row.names = c("A_23_P117082", "A_33_P3246448"))
head(exp_target_com)
#>               X06...2239_normal X06...2239_tumor Ensembl_Id HGNC
#> A_23_P117082          12.252881        12.476021       <NA> <NA>
#> A_33_P3246448          8.252989         6.085048       <NA> <NA>
probe_anno = structure(c("A_23_P117082", "A_33_P3246448", "NM_015987", "NM_080671", "NM_015987", "NM_080671", "ENSG00000013583", "ENSG00000152049", 
"HEBP1", "KCNE4"), .Dim = c(2L, 5L), .Dimnames = list(c("44693", 
"31857"), c("Probe.ID", "SystematicName", "refseq_biomart", "Ensembl_Id", 
"HGNC")))
probe_anno
#>            Probe.ID SystematicName refseq_biomart      Ensembl_Id  HGNC
#> 44693  A_23_P117082      NM_015987      NM_015987 ENSG00000013583 HEBP1
#> 31857 A_33_P3246448      NM_080671      NM_080671 ENSG00000152049 KCNE4
for(i in 1:nrow(exp_target_com)) {
  pos <- which(as.character(probe_anno$Probe.ID) == rownames(exp_target_com)[i])
  if(length(pos) > 0) {
    exp_target_com[i,3] <- as.character(probe_anno$Ensembl_Id)[pos[1]]
    exp_target_com[i,4] <- as.character(probe_anno$HGNC)[pos[1]]
    }
 }
Here is the function and apply
get_anno <- function(data_row, probe_anno) {
  pos <- which(as.character(probe_anno$Probe.ID) == rownames(data_row))
  if (length(pos) > 0) {
    data_row$Ensembl_Id <- as.character(probe_anno$Ensembl_Id)[pos[1]]
    data_row$HGNC <- as.character(probe_anno$HGNC)[pos[1]]
  }
  return(data_row) 
}
apply(exp_target_com, c(1,2), FUN = function(x) get_anno(x, probe_anno))
 
     
    