rreplacena

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


I want to replace the NA value in dfABy from the column A, with the value from the column B, based on the year of column year. For example, my df is:

                 >dfABy 
                 A    B   Year
                 56   75  1921
                 NA   45  1921
                 NA   77  1922
                 67   41  1923
                 NA   65  1923

The result what I will attend is:

                 > dfABy
                 A    B   Year
                 56   75  1921
                *45*  45  1921
                *77*  77  1922
                 67   41  1923
                *65*  65  1923

P.S: with the * the value replacing in column A from column B for every year


Solution

  • 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)