在不同数据框中匹配多列并获取其他列作为结果

14

我有两个大数据框,其中一个 (df1) 具有以下结构

   chr    init
1  12  25289552
2   3 180418785
3   3 180434779

另一个数据框(df2)包含以下内容

    V1    V2     V3
10  1     69094 medium
11  1     69094 medium
12  12 25289552 high
13  1     69095 medium
14  3 180418785 medium
15  3 180434779 low
我想要做的是将df2V3列添加到df1中,以获取变异信息。
   chr    init  Mut
1  12  25289552 high
2   3 180418785 medium
3   3 180434779 low
我正在尝试将它们加载到 R 中,然后使用 match 函数进行 for 循环,但它不起作用。你知道有什么特殊的方法可以做到这一点吗?我也可以考虑使用 awk 或类似的工具来处理。
5个回答

20

使用merge

df1 <- read.table(text='  chr    init
1  12  25289552
2   3 180418785
3   3 180434779', header=TRUE)


df2 <- read.table(text='    V1    V2     V3
10  1     69094 medium
11  1     69094 medium
12  12 25289552 high
13  1     69095 medium
14  3 180418785 medium
15  3 180434779 low', header=TRUE)


merge(df1, df2, by.x='init', by.y='V2') # this works!
       init chr V1     V3
1  25289552  12 12   high
2 180418785   3  3 medium
3 180434779   3  3    low
为了得到您所展示的期望输出方式。
output <- merge(df1, df2, by.x='init', by.y='V2')[, c(2,1,4)]
colnames(output)[3] <- 'Mut' 
output
  chr      init    Mut
1  12  25289552   high
2   3 180418785 medium
3   3 180434779    low

4
是的,这就是我想要的。关键是我还必须考虑染色体,所以可能需要像这样合并:merge(df1, df2, by.x=c('chr','init'), by.y=c('V1',V2')[, c(2,1,4)]。 - user976991
1
准确地说,只需将chrV1添加到参数中即可考虑它们:D 如果您发现有用,请考虑为有用的答案点赞并接受其中之一:D - Jilber Urbina

3
df1 <- read.table(textConnection("   chr    init
 1  12  25289552
 2   3 180418785
 3   3 180434779"), header=T)

df2 <- read.table(textConnection("    V1    V2     V3
 10  1     69094 medium
 11  1     69094 medium
 12  12 25289552 high
 13  1     69095 medium
 14  3 180418785 medium
 15  3 180434779 low"), header=T)

# You have to select the values of df2$V3 such as their corresponding V2 
# are equal to the values of df1$init
df1$Mut <- df2$V3[ df2$V2 %in% df1$init]

df1
  chr      init    Mut
1  12  25289552   high
2   3 180418785 medium
3   3 180434779    low

2
请注意,如果df1中有任何键值在df2中不存在,则此方法将无法正常工作。您将会收到一个错误提示,类似于“replacement has 3 rows, data has 4”。请参考https://dev59.com/1nM_5IYBdhLWcg3wn0lO#38130460,了解如何使用`match()`实现左连接。 - bgoldst

0

这个

df3 <- merge( df1, df2, by.x = "init", by.y = "V2" )
df3 <- df3[-3]
colnames( df3 )[3] <- "Mut"

给你想要的东西?


0

最近我遇到了一个问题,最终我创建了一个新的数据集列,并将其用作单个列进行连接。

#create new column for join
df1$id <- paste0("chr" , "init")
df2$id <- paste0("V1","V2") 
# join and select outputs
df3 <-  dplyr::left_join(x = df1, y = df2, by = "id")%>%
 dplyr::select(chr, init, V3)

这对我很有帮助。


0

@user976991的评论对我有用。

同样的想法,但需要匹配两列。

我的领域背景是一个产品数据库,其中有多个条目(可能是价格条目)。希望删除旧的update_nums,并仅保留按product_id最近的更新。

raw_data <- data.table( product_id = sample(10:13, 20, TRUE), update_num = sample(1:3, 20, TRUE), stuff = rep(1, 20, sep = ''))
max_update_nums <- raw_data[ , max(update_num), by = product_id]
distinct(merge(dt, max_update_nums, by.x = c("product_id", "update_num"), by.y = c("product_id", "V1")))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接