How to fill NAs with LOCF by factors in data frame, split by country

后端 未结 8 1949
谎友^
谎友^ 2020-12-08 05:01

I have the following data frame (simplified) with the country variable as a factor and the value variable has missing values:

country value
AUT     NA
AUT            


        
8条回答
  •  太阳男子
    2020-12-08 05:46

    If speed is a consideration then this unstack/stack solution is about 4 to 6 times faster than the others on my system although it does entail a slightly longer line of code:

    stack(lapply(unstack(data, value ~ country), na.locf, na.rm = FALSE))
    

    Another approach is:

    transform(data, value = ave(value, country, FUN = na.locf0))
    

提交回复
热议问题