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

后端 未结 8 1951
谎友^
谎友^ 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:58

    The tidyverse way, albeit not using locf, is:

    library(tidyverse)
    
    data %>% 
        group_by(country) %>% 
        fill(value)
    
    Source: local data frame [9 x 2]
    Groups: country [2]
    
    country value
    (fctr) (dbl)
    1     AUT    NA
    2     AUT     5
    3     AUT     5
    4     AUT     5
    5     GER    NA
    6     GER    NA
    7     GER     7
    8     GER     7
    9     GER     7
    
    0 讨论(0)
  • 2020-12-08 06:04

    A modern version of the ddply solution is to use the package dplyr:

    library(dplyr)
    DF %>%
      group_by(county) %>% 
      mutate(value = na.locf(value, na.rm = F))      
    
    0 讨论(0)
提交回复
热议问题