R: replacing NAs in a data.frame with values in the same position in another dataframe

前端 未结 4 1799
情话喂你
情话喂你 2020-12-09 16:22

I have a dataframe with some NA values:

dfa <- data.frame(a=c(1,NA,3,4,5,NA),b=c(1,5,NA,NA,8,9),c=c(7,NA,NA,NA,2,NA))
dfa

I would like t

4条回答
  •  难免孤独
    2020-12-09 17:18

    In the tidyverse, you can use purrr::map2_df, which is a strictly bivariate version of mapply that simplifies to a data.frame, and dplyr::coalesce, which replaces NA values in its first argument with the corresponding ones in the second.

    library(tidyverse)
    
    dfrepair %>% 
        mutate_all(as.numeric) %>%    # coalesce is strict about types
        map2_df(dfa, ., coalesce)
    
    ## # A tibble: 6 × 3
    ##       a     b     c
    ##     
    ## 1     1     1     7
    ## 2     3     5     7
    ## 3     3     4     6
    ## 4     4     3     5
    ## 5     5     8     2
    ## 6     7     9     3
    

提交回复
热议问题