Replace NA values in column with value in row above +1

for-loop, na, r, zoo

Solution

Using dplyr group and cumsum:

library(dplyr)

df1 %>% 
  group_by(game) %>% 
  mutate(shot_number_new = cumsum(is.na(shot_number)) + 1)

# Source: local data frame [8 x 3]
# Groups: game [4]
# 
#     game shot_number shot_number_new
#   <fctr>       <dbl>           <dbl>
# 1  game1           1               1
# 2  game1          NA               2
# 3  game2           1               1
# 4  game2          NA               2
# 5  game2          NA               3
# 6  game3           1               1
# 7  game4           1               1
# 8  game4          NA               2

Problem

I have the following data frame: ``` game <- c('game1','game1','game2','game2','game2','game3','game4', 'game4') shot_number <- c(1,NA,1,NA,NA,1,1,NA) df <- data.frame(game, shot_number) game shot_number game1 1 game1 NA game2 1 game2 NA game2 NA game3 1 game4 1 game4 NA ``` I want to fill the NAs by adding 1 to the value in the row above, so the df reads as follows: ``` game shot_number game1 1 game1 2 game2 1 game2 2 game2 3 game3 1 game4 1 game4 2 ``` I don't know if there's some way to do this using the 'zoo' library and na.locf or if I would need to write a for loop or some kind of function.

Original source