replace NA value with the group value

Try ave. It applies a function to groups. Have a look at ?ave for details, e.g.: df$med_card_new <- ave(df$med_card, df$hhold_no, FUN=function(x)unique(x[!is.na(x)])) # person_id hhold_no med_card med_card_new #1 1 1 1 1 #2 2 1 1 1 #3 3 1 NA 1 #4 4 1 NA 1 #5 5 1 NA 1 #6 6 2 0 … Read more