【问题标题】:R: Merging two dataframes based on mtaching values across three different columnsR:基于三个不同列的匹配值合并两个数据帧
【发布时间】:2020-10-10 08:18:41
【问题描述】:

我有两个数据框,我正在尝试根据 MarkerName、Allele1 和 Allele2 合并它们。我的问题是等位基因 1 和等位基因 2 列有时可以翻转并且是不同的情况(即下面两个示例中的第 1 行)。此外,有时 MarkerName 可能会重复(第 3 行和第 4 行)。

以下是示例:

 MarkerName  id     Allele1 Allele2
1: 1:752721  rs3131972  A  G
2: 1:791853  rs6684487  G  A
3: 1:834056 rs28482280  A  C
4: 1:834056 rs28482282  A  CAC
5: 1:834059 rs28482242  A  C,G


   MarkerName Allele1 Allele2  Effect 
1:   1:752721       g       a -0.0018 
2:   1:791853       g       a  0.0408 
3:   1:834056       a       c  0.0079 

有没有办法将 id 列添加到 R 中的第二个数据框?所以它最终看起来像这样:

   MarkerName Allele1 Allele2  Effect id
1:   1:752721       g       a -0.0018 rs3131972
2:   1:791853       g       a  0.0408 rs6684487
3:   1:834056       a       c  0.0079 rs28482280



【问题讨论】:

  • 你会想要使用 dplyr,here 是一个基于多列使用 dplyr 连接的链接
  • 输出看起来是data.table(不是data.frame)。

标签: r merge


【解决方案1】:

您可以使用pminpmaxAllele1Allele2中的数据进行排序,使用separate_rows获取不同行中的数据并将它们连接起来。

library(dplyr)

df1 %>%
   tidyr::separate_rows(Allele2) %>%
   mutate(col1 = tolower(pmin(Allele1, Allele2)), 
          col2 = tolower(pmax(Allele1, Allele2))) %>%
   right_join(df2 %>%
               mutate(col1 = tolower(pmin(Allele1, Allele2)), 
                      col2 = tolower(pmax(Allele1, Allele2))),  
                by = c('MarkerName', 'col1', 'col2')) %>%
    select(MarkerName, id, Allele1 = Allele1.y, Allele2 = Allele2.y, Effect)


#  MarkerName         id Allele1 Allele2  Effect
#1   1:752721  rs3131972       g       a -0.0018
#2   1:791853  rs6684487       g       a  0.0408
#3   1:834056 rs28482280       a       c  0.0079

【讨论】:

  • 谢谢!但问题是它重新排列等位基因 1 和 2 的顺序,这意味着我还必须为已翻转的效果列翻转符号。有没有不用改顺序就可以合并的?
  • @Parfait 这是因为在mutate 中,当您运行Allele1 = tolower(pmin(Allele1, Allele2)) 时,Allele1 的值在下一行Allele2 = tolower(pmax(Allele1, Allele2)) 中发生了更改。 transform 的情况并非如此。虽然 OP 想要保持原来的顺序,但我已经用 mutate 创建了新列,这不会弄乱 Allele1Allele2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
  • 2018-03-18
  • 1970-01-01
  • 2021-11-02
相关资源
最近更新 更多