R fill in NA with previous row value with condition

前端 未结 2 1765
深忆病人
深忆病人 2021-02-10 05:49

I need to fill in NA rows with the previous row value, but only until a criteria is not changed. As a simple example for days of week, meals and prices:

Day = c(         


        
相关标签:
2条回答
  • 2021-02-10 05:57

    You could try

    library(zoo)
    library(dplyr)
    df %>% 
         group_by(Meal) %>% 
         mutate(Price= ifelse(any(!is.na(Price)), na.locf(na.locf(Price, 
                        fromLast=TRUE, na.rm=FALSE)), NA_real_))
    #     Meal  Day Price
    #1     B  Mon    20
    #2     B Tues    20
    #3     B  Wed    20
    #4     B Thus    20
    #5     B  Fri    20
    #6     D  Sat    15
    #7     D  Sun    15
    #8     D  Mon    15
    #9     D Tues    15
    #10    L  Wed    10
    #11    L Thus    10
    #12    L  Fri    10
    #13    L  Sat    10
    #14    L  Sun    10
    
    0 讨论(0)
  • 2021-02-10 06:09

    Another option using data.table

    library(data.table)
    library(xts)
    
    dt <- data.table(df)
    
    dt[, Price := na.locf(Price, fromLast = TRUE), by = Meal]
    
    0 讨论(0)
提交回复
热议问题