R fill in NA with previous row value with condition -



R fill in NA with previous row value with condition -

i need fill in na rows previous row value, until criteria not changed. simple illustration days of week, meals , prices:

day = c("mon", "tues", "wed", "thus", "fri", "sat","sun","mon", "tues", "wed", "thus", "fri", "sat","sun") meal = c("b","b","b","b","b","d","d","d","d","l","l", "l","l","l") cost = c(na, 20, na,na,na,na,na,15,na,na,10,10,na,10) df = data.frame(meal,day ,price ) df meal day cost 1 b mon na 2 b tues 20 3 b wed na 4 b na 5 b fri na 6 d sat na 7 d sun na 8 d mon 15 9 d tues na 10 l wed na 11 l 10 12 l fri 10 13 l sat na 14 l sun 10

i need fill in na previous same meal type, on week.

i have tried

na.locf(df, fromlast = true) meal day cost 1 b mon 20 2 b tues 20 3 b wed 15 4 b 15 5 b fri 15 6 d sat 15 7 d sun 15 8 d mon 15 9 d tues 10 10 l wed 10 11 l 10 12 l fri 10 13 l sat 10 14 l sun 10

which wrong overlaps meal type. info should this:

meal day cost 1 b mon 20 2 b tues 20 3 b wed 20 4 b 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 10 12 l fri 10 13 l sat 10 14 l sun 10

many thanks

another alternative using data.table

library(data.table) library(xts) dt <- data.table(df) dt[, cost := na.locf(price, fromlast = true), = meal]

r na

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -