Search code examples
rreplacetidyversestata

R tidyverse equivalent to Stata replace if missing


I am trying to find an R/tidyverse equivalent to Stata's replace b = a if missing(b).

Say I have these data:

library(tidyverse)
data <- data.frame(a=c(1:8), b= c(1:5, NA, NA, NA))

I am trying to replace the missing values in b with the values in a. I try this:

data %<>% mutate(b = replace_na(b, a))

But get an error. What can I do in the tidyverse to solve this problem?


Solution

  • The way you're going about it I'd use coalesce from dplyr:

    data %<>% mutate(b = coalesce(b, a))
    

    Output:

    data
    
      a b
    1 1 1
    2 2 2
    3 3 3
    4 4 4
    5 5 5
    6 6 6
    7 7 7
    8 8 8