Home > Blockchain >  R: Set next row to NA in group_by
R: Set next row to NA in group_by

Time:02-04

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))

CodePudding user response:

Use cumany:

library(dplyr)
dfeg %>% 
  group_by(id) %>% 
  mutate(y = ifelse(cumany(is.na(x)), NA, x))

   id        x     y
   <chr> <dbl> <dbl>
 1 A         1     1
 2 A         2     2
 3 A        NA    NA
 4 A        NA    NA
 5 A         3    NA
 6 A         4    NA
 7 B        15    15
 8 B        16    16
 9 B        NA    NA
10 B        NA    NA
11 B        17    NA
12 B        18    NA

Previous answer:

Use an ifelse statement with lag:

library(dplyr)
dfeg %>% 
  group_by(id) %>% 
  mutate(y = ifelse(is.na(lag(x, default = 0)), NA, x))
  •  Tags:  
  • Related