Miguel de Deus Miguel de Deus - 3 years ago 236
R Question

Fill NA row with previous value iteratively in R

Say you have something like this across various weeks in a given df:

DoW Value
Mon 1234
Tue NA
Wed 5678
Thu 9123
Fri 4567
Sat 8912
Sun 3456


I'd like to fill every Tuesday's NA with Monday's value of it's correspondent week. How can I do this, preferably with the least amount of code possible?

Thanks.

Answer Source

What about this ?

mydf <- structure(list(DoW = c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", 
"Sun"), Value = c(1234L, NA, 5678L, 9123L, 4567L, 8912L, 3456L
)), .Names = c("DoW", "Value"), class = "data.frame", row.names = c(NA, 
-7L))

tuesd_na <- which(mydf$DoW == "Tue" & is.na(mydf$Value))
mydf$Value[tuesd_na] <- mydf$Value[tuesd_na - 1]
mydf
#>   DoW Value
#> 1 Mon  1234
#> 2 Tue  1234
#> 3 Wed  5678
#> 4 Thu  9123
#> 5 Fri  4567
#> 6 Sat  8912
#> 7 Sun  3456
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download