繁体   English   中英

R dplyr左连接多个表,没有两个带后缀的单独列

[英]R dplyr left join multiple tables without two separate columns with suffix

假设我有一个主表 x

x <- tibble(id = c(1,2,3,4,5), score = c(100,200,300,100,200))
x
# A tibble: 5 x 2
     id score
  <dbl> <dbl>
1     1   100
2     2   200
3     3   300
4     4   100
5     5   200

和另外两张桌子

y = tibble(id = c(1,2), score_new=c(200,300))
y
# A tibble: 2 x 2
     id score_new
  <dbl>     <dbl>
1     1       200
2     2       300

z = tibble(id = c(3,4), score_new = c(300,400))
z
# A tibble: 2 x 2
     id score_new
  <dbl>     <dbl>
1     3       300
2     4       400

如果我将它们连接在一起,它将是这样的:

x %>% left_join(y, by =c("id" = "id")) %>% left_join(z, by =c("id" = "id"))
# A tibble: 5 x 4
     id score score_new.x score_new.y
  <dbl> <dbl>       <dbl>       <dbl>
1     1   100         200          NA
2     2   200         300          NA
3     3   300          NA         300
4     4   100          NA         400
5     5   200          NA          NA

但我需要score_new只有一列。 我怎么做? 对不起,如果已经有其他类似的问题,但我真的找不到它们。

您可以通过附加 y 和 z 然后加入它们来实现。

# Loading required libraries
library(dplyr)

# Create sample df
x <- tibble(id = c(1,2,3,4,5), score = c(100,200,300,100,200))
y = tibble(id = c(1,2), score_new=c(200,300))
z = tibble(id = c(3,4), score_new = c(300,400))

x %>%
  # union y and z and join on x to get new scores
  left_join(union_all(y,z), by = "id")

同样,您可以使用 bind_rows 而不是 union_all 在这种情况下都给出相同的结果。

x %>%
  # union y and z and join on x to get new scores
  left_join(bind_rows(y,z), by = "id")

你可以试试这个方法:

mutate(score_new.x = if_else(is.na(score_new.x),score_new.y,score_new.x)) %>%
select(-score_new.y)

我参加聚会有点晚了。 但我会选择这个tidyverse解决方案,

bind_rows(
        y,z
) %>% left_join(x = x)

这给出了以下output

# A tibble: 5 x 3
     id score score_new
  <dbl> <dbl>     <dbl>
1     1   100       200
2     2   200       300
3     3   300       300
4     4   100       400
5     5   200        NA

注意: left_join()xy参数,这里我指定了x = x ,其中 rhs 是您的数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM