Search code examples
rconditional-statementsrecode

How to replace value in a variable based on matching values in another variable in R?


Suppose I have NA values under a variable, Font in my df. How can replace the NA values based on matching values under the variable, Group? For instance, I want all rows where Group = 1 to have Arial as the Font and all rows where Group = 2 to have Helvetica as the Font. I am aware that I can do the following: df$Font[df$Group==1]<-"Arial" or use recode() from the 'car' package. However, suppose that there are thousands of different groups and fonts, and I don't want to keep typing each of them out in my code.

Example data:
   Group  Font
   1      Arial
   1      NA
   2      NA
   2      Helvetica

Solution

  • Use ave to grab a non-missing value and fill:

    dat <- read.table(text="   Group  Font
       1      Arial
       1      NA
       2      NA
       2      Helvetica",header=TRUE)
    
    dat$Font <- with(dat, ave(Font, Group, FUN=function(x) replace(x, TRUE, na.omit(x)[1L])))
    
    #  Group      Font
    #1     1     Arial
    #2     1     Arial
    #3     2 Helvetica
    #4     2 Helvetica