R fill in NA with previous row value with condition

梦想与她 提交于 2019-12-03 16:26:23

Another option using data.table

library(data.table)
library(xts)

dt <- data.table(df)

dt[, Price := na.locf(Price, fromLast = TRUE), by = Meal]

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!