Replace a value NA with the value from another column in R

Perhaps the easiest to read/understand answer in R lexicon is to use ifelse. So borrowing Richard's dataframe we could do:

df <- structure(list(A = c(56L, NA, NA, 67L, NA),
                     B = c(75L, 45L, 77L, 41L, 65L),
                     Year = c(1921L, 1921L, 1922L, 1923L, 1923L)),.Names = c("A", 
                                                                                                                            "B", "Year"), class = "data.frame", row.names = c(NA, -5L))
df$A <- ifelse(is.na(df$A), df$B, df$A)

The solution provided by GGAnderson did return an error message. Using it inside mutate() however worked fine.

df <- structure(list(A = c(56L, NA, NA, 67L, NA),
                     B = c(75L, 45L, 77L, 41L, 65L),
                     Year = c(1921L, 1921L, 1922L, 1923L, 1923L)),
                .Names = c("A", "B", "Year"), 
                class = "data.frame", 
                row.names = c(NA, -5L))
df
df%>% 
  coalesce(A,B) #returns error

df %>%
mutate(A = coalesce(A,B)) #works

(I am new to Stackoverflow; My low reputation does not allow to comment on GGAnderson´s answer directly)


Now corrected per @Max. (original worked with initial implementation)

The new dplyr function, coalesce, can really simplify these situations.

library(dplyr)

dfABy %>% 
    mutate(A = coalesce(A,B))

Tags:

Replace

R

Na