replace NA value with the group value

后端 未结 5 715
栀梦
栀梦 2020-11-27 22:15

I have a df as follows which has 20 people across 5 households. Some people within the household have missing data for whether they have a med_card or not. I want to give th

5条回答
  •  萌比男神i
    2020-11-27 22:18

    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            0
    #7          7        2        0            0
    #8          8        2        0            0
    #9          9        2        0            0
    

    Please note that this will only work if not all values in a household are NA and the should not differ (e.g. person 1 == 1, person 2 == 0).

提交回复
热议问题