匹配 2 个不同文件和 2 列中的相同行

问题描述 投票:0回答:1

我有两个文件,我想根据前两列合并它们,如果行匹配,并将file2的第三列添加到file1。

文件1

CHR BP SNP ZSCORE
1   2534 rs123 0.5
1   2860 rs225 0.1
1   10000 rs356 0.8

文件2

CHR BP AF
1   2534 0.02
1   6538 0.1
1   12345 0.1

所以我想要的是:

文件3

CHR BP SNP ZSCORE AF
1   2534 rs123 0.5 0.02

我尝试了 R 的合并,但它导致仅将新数据集中的列添加在一起:

merged<-merge(File1, File2, by.x = "BP", by.y = "CHR", all = TRUE)
merged<-merge(File1, File2, by.x = "CHR", by.y = "BP", all = TRUE)

命令 merge 的下一版本产生了额外的行,我认为这是不正确的 - 如何将 1700 万行的文件与 17,200,000 行的文件匹配产生 18,000,000 行?!

merged <- merge(File1[c('CHR','BP')],File2)

尝试过 dplyr 左连接:

merged<-dplyr::left_join(File1, File2, by = c("CHR", "BP"))
Warning message:
In dplyr::left_join(File1, File2, by = c("CHR", "BP")) :
  Detected an unexpected many-to-many relationship between `x` and `y`.
ℹ Row 5 of `x` matches multiple rows in `y`.
ℹ Row 3570136 of `y` matches multiple rows in `x`.
ℹ If a many-to-many relationship is expected, set `relationship = "many-to-many"` to silence this warning.

反转文件会导致同样的错误。

我也尝试过各种版本的awk和join,但没有产生我想要的。

如果有人知道解决方案,请告诉我,无论它是 R 代码还是 awk/join-all 都适合我。

r linux merge match multiple-columns
1个回答
1
投票

使用最后注释中的输入

merge(File1, File2, by = 1:2)

给予:

  CHR   BP   SNP ZSCORE   AF
1   1 2534 rs123    0.5 0.02

注意

Lines1 <- "
CHR BP SNP ZSCORE
1   2534 rs123 0.5
1   2860 rs225 0.1
1   10000 rs356 0.8e"

Lines2 <- "CHR BP AF
1   2534 0.02
1   6538 0.1
1   12345 0.1"

File1 <- read.table(text = Lines1, header = TRUE)
File2 <- read.table(text = Lines2, header = TRUE)
© www.soinside.com 2019 - 2024. All rights reserved.