I have a dataset where I want to replace each zero
with incrementing values: the first zero becomes 0.001, the second 0.002, the third 0.003, and so on. Each time a zero appears, it should increase by 0.001 from the previous replacement.
set.seed(123)
DF <- data.frame(Year = 1981:2000, Value = sample(0:5, 20, replace = T))
library(dplyr)
DF %>%
filter(Value != 0) %>%
rbind(.,
DF %>%
filter(Value == 0) %>%
mutate(Value = cumsum(Value + .001))) %>%
arrange(Year)
Year Value
1 1981 2.000
2 1982 5.000
3 1983 2.000
4 1984 1.000
5 1985 1.000
6 1986 5.000
7 1987 2.000
8 1988 4.000
9 1989 3.000
10 1990 5.000
11 1991 5.000
12 1992 0.001
13 1993 1.000
14 1994 2.000
15 1995 4.000
16 1996 2.000
17 1997 2.000
18 1998 0.002
19 1999 3.000
20 2000 0.003