簡體   English   中英

left_join 兩個數據幀並覆蓋

[英]left_join two data frames and overwrite

我想合並兩個數據幀,其中df2覆蓋NAdf1存在的任何值。 合並數據幀和覆蓋值提供了data.table選項,但我想知道是否有辦法用dplyr做到這dplyr 我已經嘗試了所有_join選項,但似乎沒有一個能做到這一點。 有沒有辦法用dplyr做到這dplyr

下面是一個例子:

df1 <- data.frame(y = c("A", "B", "C", "D"), x1 = c(1,2,NA, 4)) 
df2 <- data.frame(y = c("A", "B", "C"), x1 = c(5, 6, 7))

期望的輸出:

  y x1
1 A  5
2 B  6
3 C  7
4 D  4

我認為您想要的是保留df2的值,並且只添加df1中不存在於df2中的df2 ,這就是anti_join作用:

“anti_join 返回 x 中沒有匹配值的所有行,只保留 x 中的列。”

我的解決方案:

df3 <- anti_join(df1, df2, by = "y") %>% bind_rows(df2)

Warning messages:
1: In anti_join_impl(x, y, by$x, by$y) :
  joining factors with different levels, coercing to character vector
2: In rbind_all(x, .id) : Unequal factor levels: coercing to character

> df3
Source: local data frame [4 x 2]

      y    x1
  (chr) (dbl)
1     D     4
2     A     5
3     B     6
4     C     7

此行提供了所需的輸出(以不同的順序),但是,您應該注意警告消息,在處理數據集時,請務必將y讀取為字符變量。

這是我現在使用的習慣用法,因為此外,它處理保留不屬於更新表的列。 我使用了一些與 OP 不同的名稱,但味道相似。

我做的一件事是為連接中使用的鍵創建一個變量,因為我在幾個地方使用它。 但除此之外,它會執行所需的操作。

它本身不處理例如“如果值為 NA 則更新此行”的操作,但您應該在創建連接表時執行該條件。

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

.keys <- c("key1", "key2")

.base_table <- tribble(
    ~key1, ~key2, ~val1, ~val2,
    "A", "a", 0, 0,
    "A", "b", 0, 1,
    "B", "a", 1, 0,
    "B", "b", 1, 1)

.join_table <- tribble(
    ~key1, ~key2, ~val2,
    "A", "b", 100,
    "B", "a", 111)

# This works
df_result <- .base_table %>%
    # Pull off rows from base table that match the join table
    semi_join(.join_table, .keys) %>%
    # Drop cols from base table that are in join table, except for the key columns
    select(-matches(setdiff(names(.join_table), .keys))) %>%
    # Left join on the join table columns
    left_join(.join_table, .keys) %>%
    # Remove the matching rows from the base table, and bind on the newly joined result from above.
    bind_rows(.base_table %>% anti_join(.join_table, .keys))

df_result %>%
    print()
#> # A tibble: 4 x 4
#>   key1  key2   val1  val2
#>   <chr> <chr> <dbl> <dbl>
#> 1 A     b         0   100
#> 2 B     a         1   111
#> 3 A     a         0     0
#> 4 B     b         1     1

reprex 包(v0.3.0) 於 2019 年 12 月 12 日創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM