I have a dataset where I want to replace NAs with the preceding character string:
d <- data.frame(X = c("one", NA, "two", NA, "three", NA), Y = c(1:6),
stringsAsFactors = FALSE)
> d
X Y
1 one 1
2 <NA> 2
3 two 3
4 <NA> 4
5 three 5
6 <NA> 6
I came up with the following solution which seems lousy somehow:
v <- c()
for (i in seq_along(1:nrow(d))){
v[i] <- ifelse(is.na(d$X[i]) == TRUE, d$X[i-1], d$X[i])
}
d$X2 <- v
d
X Y X2
1 one 1 one
2 <NA> 2 one
3 two 3 two
4 <NA> 4 two
5 three 5 three
6 <NA> 6 three
My question: Is there a better way to do this and how could this be implemented in a dplyr pipe?