replace NA value with the group value

后端 未结 5 716
栀梦
栀梦 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条回答
  •  爱一瞬间的悲伤
    2020-11-27 22:31

    That is exactly what na.aggregate (link) in the zoo package does:

    library(zoo)
    
    transform(df, med_card_new = na.aggregate(med_card, by = hhold_no))
    

    This uses mean; however, you can specify any function you like. For example, if you prefer to return an NA if all items in a group are NA (rather than NaN which is what mean would return if given a zero length vector) then

    meanNA <- function(x, ...) if (all(is.na(x))) NA else mean(x, ...)
    transform(df, med_card_new = na.aggregate(med_card, by = hhold_no, FUN = meanNA))
    

提交回复
热议问题