【问题标题】:How to replace columns with NA in a tibble with imputed columns from another tibble in R如何用 R 中另一个 tibble 的估算列替换 tibble 中的 NA 列
【发布时间】:2021-06-17 10:58:40
【问题描述】:

我想用df 中的NA 替换de 列,使用df2 中的估算值得到df3。 我可以用left_joincoalesce 做到这一点,但我认为这种方法不能很好地推广。有没有更好的办法?

library(tidyverse)

df <- tibble(c = c("a", "a", "a", "b", "b", "b"),
             d = c(1, 2, 3, 1, 2, 3),
             x = c(1, NA, 3, 4, 5,6),
             y = c(1, 2, NA, 4, 5, 6),
             z = c(1, 2, 7, 4, 5, 6))

# I want to replace NA in df by df2

df2 <- tibble(c = c("a", "a", "a"),
             d = c(1, 2, 3),
             x = c(1, 2, 3),
             y = c(1, 2, 2))

# to get

df3 <- tibble(c = c("a", "a", "a", "b", "b", "b"),
             d = c(1, 2, 3, 1, 2, 3),
             x = c(1, 2, 3, 4, 5, 6),
             y = c(1, 2, 2, 4, 5, 6),
             z = c(1, 2, 7, 4, 5, 6))

# is there a better solution than coalesce?

df3 <- df %>% left_join(df2, by = c("c", "d")) %>%
  mutate(x = coalesce(x.x, x.y),
         y = coalesce(y.x, y.y)) %>%
  select(-x.x, -x.y, -y.x, -y.y)
Created on 2021-06-17 by the reprex package (v2.0.0)

【问题讨论】:

  • 所以您正在寻找一个函数,该函数显示“在指定列上连接两个数据帧,并使用第二个数据帧从第一个数据帧中填充缺失的条目”
  • 更好:一个“在指定列上连接两个数据帧并使用第二个数据帧替换第一个数据帧中缺失条目的列”的函数

标签: r join replace coalesce


【解决方案1】:

这是一个合并所有 .x.y 列的自定义函数,可选择重命名和删除列。

#' Coalesce all columns duplicated in a previous join.
#'
#' Find all columns resulting from duplicate names after a join
#' operation (e.g., `dplyr::*_join` or `base::merge`), then coalesce
#' them pairwise.
#'
#' @param x data.frame
#' @param suffix character, length 2, the same string suffixes
#'   appended to column names of duplicate columns; should be the same
#'   as provided to `dplyr::*_join(., suffix=)` or `base::merge(.,
#'   suffixes=)`
#' @param clean logical, whether to remove the suffixes from the LHS
#'   columns and remove the columns on the RHS columns
#' @param strict logical, whether to enforce same-classes in the LHS
#'   (".x") and RHS (".y") columns; while it is safer to set this to
#'   true (default), sometimes the conversion of classes might be
#'   acceptable, for instance, if one '.x' column is 'numeric' and its
#'   corresponding '.y' column is 'integer', then relaxing the class
#'   requirement might be acceptable
#' @return 'x', coalesced, optionally cleaned
#' @export
coalesce_all <- function(x, suffix = c(".x", ".y"),
                         clean = FALSE, strict = TRUE) {
  nms <- colnames(x)
  Xs <- endsWith(nms, suffix[1])
  Ys <- endsWith(nms, suffix[2])
  # x[Xs] <- Map(dplyr::coalesce, x[Xs], x[Ys])
  # x[Xs] <- Map(data.table::fcoalesce, x[Xs], x[Ys])
  x[Xs] <- Map(function(dotx, doty) {
    if (strict) stopifnot(identical(class(dotx), class(doty)))
    isna <- is.na(dotx)
    replace(dotx, isna, doty[isna])
  } , x[Xs], x[Ys])
  if (clean) {
    names(x)[Xs] <- gsub(glob2rx(paste0("*", suffix[1]), trim.head = TRUE), "", nms[Xs])
    x[Ys] <- NULL
  }
  x
}

在行动:

df %>%
  left_join(df2, by = c("c", "d")) %>%
  coalesce_all()
# # A tibble: 6 x 7
#   c         d   x.x   y.x     z   x.y   y.y
#   <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 a         1     1     1     1     1     1
# 2 a         2     2     2     2     2     2
# 3 a         3     3     2     7     3     2
# 4 b         1     4     4     4    NA    NA
# 5 b         2     5     5     5    NA    NA
# 6 b         3     6     6     6    NA    NA

df %>%
  left_join(df2, by = c("c", "d")) %>%
  coalesce_all(clean = TRUE)
# # A tibble: 6 x 5
#   c         d     x     y     z
#   <chr> <dbl> <dbl> <dbl> <dbl>
# 1 a         1     1     1     1
# 2 a         2     2     2     2
# 3 a         3     3     2     7
# 4 b         1     4     4     4
# 5 b         2     5     5     5
# 6 b         3     6     6     6

我在Map 中包含了两个合并函数作为base-R 的替代方法。一个优点是 strict 参数:dplyr::coalesce 将静默允许 integernumeric 合并,而 data.table::fcoalesce 不会。如果这是可取的,请使用您喜欢的。 (另一个优点是两个非基本合并函数都接受任意数量的列来合并,这在此实现中不是必需的。)

【讨论】:

    【解决方案2】:

    您可以使用across.names.keep 参数一次改变所有列,就像这样

    library(dplyr, warn.conflicts = F)
    
    df %>% left_join(df2, by = c("c", "d")) %>%
      mutate(across(ends_with('.x'), ~ coalesce(., get(gsub('.x', '.y', cur_column()))),
                    .names = '{gsub(".x$", "", .col)}'), .keep = 'unused')
    #> # A tibble: 6 x 5
    #>   c         d     z     x     y
    #>   <chr> <dbl> <dbl> <dbl> <dbl>
    #> 1 a         1     1     1     1
    #> 2 a         2     2     2     2
    #> 3 a         3     7     3     2
    #> 4 b         1     4     4     4
    #> 5 b         2     5     5     5
    #> 6 b         3     6     6     6
    

    reprex package (v2.0.0) 于 2021-06-17 创建

    【讨论】:

      【解决方案3】:

      我尝试了另一种方法,过滤c,将df 的所有列删除为NA,与df2 连接,并将未过滤的df 的行与df3 绑定。

      df3 <- df %>% filter(c == "a") %>% select_if(~ !any(is.na(.))) %>%
        left_join(df2, by = c("c", "d"))
      df3 <- bind_rows(df %>% filter(!c == "a"), df3) %>% arrange(c,d)
      df3
      #> # A tibble: 6 x 5
      #>   c         d     x     y     z
      #>   <chr> <dbl> <dbl> <dbl> <dbl>
      #> 1 a         1     1     1     1
      #> 2 a         2     2     2     2
      #> 3 a         3     3     2     7
      #> 4 b         1     4     4     4
      #> 5 b         2     5     5     5
      #> 6 b         3     6     6     6
      Created on 2021-06-17 by the reprex package (v2.0.0)
      

      【讨论】:

        【解决方案4】:

        我们可以使用 {powerjoin}

        library(powerjoin)
        power_left_join(df, df2, by = c("c", "d"), conflict = coalesce_xy)
        #> # A tibble: 6 × 5
        #>   c         d     z     x     y
        #>   <chr> <dbl> <dbl> <dbl> <dbl>
        #> 1 a         1     1     1     1
        #> 2 a         2     2     2     2
        #> 3 a         3     7     3     2
        #> 4 b         1     4     4     4
        #> 5 b         2     5     5     5
        #> 6 b         3     6     6     6
        

        【讨论】:

          猜你喜欢
          • 2022-01-13
          • 2021-07-21
          • 1970-01-01
          • 2023-03-05
          • 2021-10-17
          • 2018-05-21
          • 1970-01-01
          • 2020-12-16
          • 1970-01-01
          相关资源
          最近更新 更多