Here's a dplyr
method:
library(dplyr)
dat <- tibble(
int1 = c(0,0,0,1,1,1,0,0,0),
int2 = c(0,0,0,-1,-1,0,0,0,0)
)
dat %>%
mutate_at(vars(int1, int2), ~ if_else(. == 0 & lag(. != 0, default = FALSE) != 0, lag(.), .))
# # A tibble: 9 x 2
# int1 int2
# <dbl> <dbl>
# 1 0 0
# 2 0 0
# 3 0 0
# 4 1 -1
# 5 1 -1
# 6 1 -1
# 7 1 0
# 8 0 0
# 9 0 0
If you need these as additional columns (vice in-place replacement):
dat %>%
mutate_at(vars(int1, int2), list(fixed = ~ if_else(. == 0 & lag(. != 0, default = FALSE) != 0, lag(.), .)))
# # A tibble: 9 x 4
# int1 int2 int1_fixed int2_fixed
# <dbl> <dbl> <dbl> <dbl>
# 1 0 0 0 0
# 2 0 0 0 0
# 3 0 0 0 0
# 4 1 -1 1 -1
# 5 1 -1 1 -1
# 6 1 0 1 -1
# 7 0 0 1 0
# 8 0 0 0 0
# 9 0 0 0 0