This is my data frame:
library(zoo)
library(dplyr)
df <- data.frame(
id = rep(1:4, each = 4),
status = c(
NA, "a", "c", "a",
NA, "c", "c", "c",
NA, NA, "a", "c",
NA, NA, "c", "c"),
otherVar = letters[1:16],
stringsAsFactors = FALSE)
For the variable status I want the next observation to be carried backward within group (id).
df %>% group_by(id) %>% na.locf(fromLast = TRUE) %>% ungroup
However, I want only my "c" 's to be carried backwards but not "a" 's.
From variable status:
NA "a" "c" "a" NA "c" "c" "c" NA NA "a" "c" NA NA "c" "c"
I want to get:
NA "a" "c" "a" "c" "c" "c" "c" NA NA "a" "c" "c" "c" "c" "c"
Respectively:
data.frame(
id = rep(1:4, each = 4),
status = c(
NA, "a", "c", "a",
"c", "c", "c", "c",
NA, NA, "a", "c",
"c", "c", "c", "c"),
otherVar = letters[1:16],
stringsAsFactors = FALSE)
Is there a way of doing this?