Search code examples
rmergeadditionnacoalesce

Adding a column that contain te missing values of an specific column of a tibble in R


I am working with R. I got the missing values of a specific column in a dataset and I need add them into my main data.

My data looks like this...

A           B    C    D    G
Joseph      5    2.1  6.0  7.8
Juan        NA   3.0  3.5  3.8
Miguel      2    4.0  2.0  2.5
Steven      NA   6.0  5.0  0.2
Jennifer    NA   0.1  5.0  7.0
Emma        8.0  8.1  8.3  8.5

So, no I have the data of the missing values in column B

A          B
Juan       3.0
Steven     2.5
Jennifer   4.4

I need to add them into my main data. I tried to use the function coalesce that it is within tidyverse, but I wasn't able to get the right result.


Solution

  • One option could be:

    df %>%
     mutate(B = if_else(is.na(B), df2$B[match(A, df2$A)], B))
    
             A   B   C   D   G
    1   Joseph 5.0 2.1 6.0 7.8
    2     Juan 3.0 3.0 3.5 3.8
    3   Miguel 2.0 4.0 2.0 2.5
    4   Steven 2.5 6.0 5.0 0.2
    5 Jennifer 4.4 0.1 5.0 7.0
    6     Emma 8.0 8.1 8.3 8.5