R-收集循环输出到数据帧或单独向量中的新列中?

时间:2018-10-10 22:41:49

标签: r

我已经在R中编写了一个函数,该函数从数据框中获取鼠标蛋白的唯一标识符(例如Q8BZR4),将其与鼠标ID相同或相似人类伴侣旁边的数据框中的条目进行匹配,然后返回人的ID。我将为数百个ID执行此操作,因此理想情况下,在返回每个人类ID之后,是否可以将其输入到原始数据帧(数据)的新列中或新矢量中,以便以后将其添加到原始的数据帧会很棒。

原始鼠标数据和mouse_human伙伴数据的子集:

dput(droplevels(df_mouse))
structure(list(Protein.IDs = c("Q8CBM2;A2AL85;Q8BSY0", "A2AMH3;A2AMH5;A2AMH4;Q6X893;Q6X893-2;A2AMH8", 
"A2AMW0;P47757-2;A2AMV7;P47757;F6QJN8;F6YHZ8;F7CAZ6", "Q3U8S1;A2APM5;A2APM3;A2APM4;E9QKM8;Q80X37;A2APM1;A2APM2;P15379-2;P15379-3;P15379-6;P15379-11;P15379-5;P15379-10;P15379-9;P15379-4;P15379-8;P15379-7;P15379;P15379-12;P15379-13", 
"A2ASS6;E9Q8N1;E9Q8K5;A2ASS6-2;A2AT70;F7CR78", "A2AUR7;Q9D031;Q01730"
), Replicate = c(2L, 2L, 2L, 2L, 2L, 2L), Ratio.H.L.normalized.01 = c(NaN, 
NaN, NaN, NaN, NaN, NaN), Ratio.H.L.normalized.02 = c(NaN, NaN, 
NaN, NaN, NaN, NaN), Ratio.H.L.normalized.03 = c(NaN, NaN, NaN, 
NaN, NaN, NaN)), .Names = c("Protein.IDs", "Replicate", "Ratio.H.L.normalized.01", 
"Ratio.H.L.normalized.02", "Ratio.H.L.normalized.03"), row.names = 12:17, class = "data.frame")

dput(droplevels(df_mouse_human))
structure(list(Human = c("Q8WZ42", "Q8NF91", "Q9UPN3", "Q96RW7", 
"Q8WXG9", "P20929", "Q5T4S7", "O14686", "Q2LD37", "Q92736"), 
    Protein.IDs = c("A2ASS6", "Q6ZWR6", "Q9QXZ0", "D3YXG0", "Q8VHN7", 
    "E9Q1W3", "A2AN08", "Q6PDK2", "A2AAE1", "E9Q401")), .Names = c("Human", 
"Protein.IDs"), row.names = c(NA, 10L), class = "data.frame")

还有我正在使用的代码:

  map.ids <- function(row_nums){
  for (ii in 1:length(row_nums)){
  # Picks out the Uniprot Identifer from the data
  row_num = row_nums[ii]
  row_ids <- ((data[row_num,1]))
  # Maps the row IDs to the Human-Mouse set and extracts the Human Identifier
  mouse.id <- which(H.sapiens.M.musculus$Mouse == row_ids)
  human.id <- H.sapiens.M.musculus[mouse.id,1]
  }
  }

1 个答案:

答案 0 :(得分:1)

您应该为此任务使用mergedplyr::join

假设鼠标ID的第一个数据帧mouse_data看起来像这样:

mouse_id  value
  O35099 832077
  P97865 839677
  Q9JK95 255605
  P15261 776238
  Q3UGY8 814013
  Q60769 789965

鼠标和人类ID的第二个数据帧mouse_human_data如下所示:

   mouse_id human_id
     Q8CAF4   Q5SYE7
     Q9WU63   Q9Y5Z4
     Q3UGY8   Q5TH69
     Q9JK95   Q96FX8
     Q60769   P21580
     Q6PFG8   Q7RTU3
     P15261   P15260
     Q80XF5   Q969J5
     Q6PHB0   Q9UHF4
     Q8BGF8   Q5M8T2
     P97865   O00628
     O35099   Q99683

然后:

merge(mouse_data, mouse_human_data)

或:

library(dplyr)
mouse_data %>% 
  left_join(mouse_human_data)

将生成以下内容:

  mouse_id  value human_id
1   O35099 832077   Q99683
2   P97865 839677   O00628
3   Q9JK95 255605   Q96FX8
4   P15261 776238   P15260
5   Q3UGY8 814013   Q5TH69
6   Q60769 789965   P21580