Populate missing data based on two pre-existing factors

Viewed 77

I have a dataframe like this:

a <- c(1:9)
b <- as.factor(c("Day", "Day", NA, "Night", NA, "Day", NA, "Night", "Night"))
df<-data.frame(a=a,b=b)

I would like to conditionally replace the NA values, based on the values that already exist, in order to create this:

df$a <- c(1:9)
df$b <- as.factor("Day", "Day", "Dusk", "Night", "Dawn", "Day", "Dusk", "Night", "Night")

I've explored using na.locf() and fill() but haven't quite managed to figure out a solution yet.

1 Answers
require(dplyr)
df %>% mutate(b=as.factor(case_when(is.na(b) & lag(b)=="Day" ~ "Dusk",
                 is.na(b) & lag(b)=="Night" ~"Dawn",
                 TRUE ~ as.character(b))))

  a     b
1 1   Day
2 2   Day
3 3  Dusk
4 4 Night
5 5  Dawn
6 6   Day
7 7  Dusk
8 8 Night
9 9 Night

This approach uses dplyr to mutate b and change any NA that follows "Day" to "Dusk" and any NA that follows "Night" to "Dawn", leaving anything else as it is (including any leading NAs, if there were any).

Related