I have some zero values and would like to replace by the previous value in R.
X var : 1 3 6 0 7 8 0 0 9 8 9 0 0 0 4 7 2 4
X new var : 1 3 6 6 7 8 8 8 9 8 9 9 9 9 4 7 2 4
I have some zero values and would like to replace by the previous value in R.
X var : 1 3 6 0 7 8 0 0 9 8 9 0 0 0 4 7 2 4
X new var : 1 3 6 6 7 8 8 8 9 8 9 9 9 9 4 7 2 4
You can use the dplyr and tidyr packages.
library(dplyr)
library(tidyr)
df <- data.frame(var = c(1,2,3,0,7,8,0,0,9,8,9,0,0,0,4,7,2,4))
df <- df %>%
dplyr::mutate(var = ifelse(var == 0, NA, var)) %>%
tidyr::fill(var, .direction = c("down"))
df
> df
var
1 1
2 2
3 3
4 3
5 7
6 8
7 8
8 8
9 9
10 8
11 9
12 9
13 9
14 9
15 4
16 7
17 2
18 4