0

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.

Miguel
  • 89
  • 5
  • ``library(zoo); na.locf(DF, na.rm = FALSE)`. If the leading values cannot be NA then the `na.rm=` argument can be omitted. If you only want to apply it to one column but not others then `transform(DF, Value = na.locf0(Value))` where `na..locf0` is like `na.locf` but defaults to `na.rm=FALSE` and only handles vectors. – G. Grothendieck Dec 01 '17 at 11:48

2 Answers2

1

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
lbusett
  • 5,801
  • 2
  • 24
  • 47
-1

You can also do this with the tidyr::fill.

library('tidyverse')

df <- tribble(
  ~DoW,  ~Value,
  'Mon', 1234,
  'Tue', NA,
  'Wed', 5678,
  'Thu', 9123,
  'Fri', 4567,
  'Sat', 8912,
  'Sun', 3456
)

fill(df, Value)
# # A tibble: 7 x 2
#     DoW Value
#   <chr> <dbl>
# 1   Mon  1234
# 2   Tue  1234
# 3   Wed  5678
# 4   Thu  9123
# 5   Fri  4567
# 6   Sat  8912
# 7   Sun  3456
Paul
  • 8,734
  • 1
  • 26
  • 36