'R: Set next row to NA in group_by

I want to set the next row i+1 in the same column to NA if there is already an NA in row i and then do this by groups. Here is my attempt:

dfeg <- tibble(id = c(rep("A", 5), rep("B", 5)),
               x = c(1, 2, NA, NA, 3, 5, 6, NA, NA, 7))

setNextrowtoNA <- function(x){
  
  for (j in 1:length(x)){
    
    if(is.na(x[j])){x[j+1] <- NA}
    
  }
}

dfeg <- dfeg %>% group_by(id) %>% mutate(y = setNextrowtoNA(x))

However my attempt doesn't create the column y that am looking for. Can anyone help with this? Thanks!

EDIT: In my actual data I have multiple values in a row that need to be set to NA, for example my data is more like this:

dfeg <- tibble(id = c(rep("A", 6), rep("B", 6)),
                   x = c(1, 2, NA, NA, 3, 4, 15, 16, NA, NA, 17, 18))

And need to create a column like this:

y = c(1, 2, NA, NA, NA, NA, 15, 16, NA, NA, NA, NA)

Any ideas? Thanks!

EDIT 2:

I figured it out on my own, this seems to work:

dfeg <- tibble(id = c(rep("A", 6), rep("B", 6)),
               x = c(1, 2, NA, NA, 3, 4,  15, 16, NA, NA, 17, 18))

setNextrowtoNA <- function(x){
  
  for (j in 1:(length(x))){
    
    if(is.na(x[j]))
    {
      x[j+1] <- NA
      }
    lengthofx <- length(x)
    x <- x[-lengthofx]
    print(x[j])
  }
  return(x)
}

dfeg <- dfeg %>% group_by(id) %>% mutate(y = NA,
                                         y = setNextrowtoNA(x))


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source