I have a data frame like this:
# A tibble: 14 x 1
inventory
<int>
1 3
2 4
3 NA
4 5
5 NA
6 NA
7 NA
8 NA
9 10
10 14
11 NA
12 NA
13 NA
14 16
I want to replace NA value with the last available value.
For the row number 3 I can do as follow:
df %>%
mutate(
inventory2 = ifelse(
!is.na(inventory),
inventory,
lag(inventory)
)
)
But for row 5 to 8, I would like to keep the last value of the newly created vector inventory2
. In other words, to reference itself.
I tried the following but it doesn't work
df %>%
mutate(
inventory2 = ifelse(
!is.na(inventory),
inventory,
lag(inventory2) # reference to itself doesn't work
)
)
for loop is super slow either.
The final output should be:
# A tibble: 14 x 1
inventory inventory2
<int> <int>
1 3 3
2 4 4
3 NA 4
4 5 5
5 NA 5
6 NA 5
7 NA 5
8 NA 5
9 10 10
10 14 14
11 NA 14
12 NA 14
13 NA 14
14 16 16
Is it possible to do this?
Thanks for you help