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(
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
Another option using data.table
library(data.table)
library(xts)
dt <- data.table(df)
dt[, Price := na.locf(Price, fromLast = TRUE), by = Meal]