1

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

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.