Search code examples
rnafill

Na fill after a specific value


I would like to use NA.fill after a 1, but keep the NA’s after -1. Is there a simple solution for this?

Old New
1 1
NA 1
NA 1
NA 1
-1 -1
NA NA
NA NA
1 1
NA 1
NA 1

Reproducible example data

dat <- read.table(text = "
Old New
1   1
NA  1
NA  1
NA  1
-1  -1
NA  NA
NA  NA
1   1
NA  1
NA  1", header = TRUE)

Edit: I only had 1s and -1s in the columns. Thank you all, the answers were very helpfull. My 'New' column is now exactly how I wanted.


Solution

  • You could do this by fill and ifelse

    library(tidyverse)
    dat <- structure(list(Old = c(1L, NA, NA, NA, -1L, NA, NA, 1L, NA, NA
    )), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"
    )) 
    
    dat %>% 
    mutate(New = Old) %>% 
    fill(New) %>% 
    mutate(New = ifelse(New == -1, Old, New)) %>% 
    select(Old, New)
    

    Result:

    # A tibble: 10 x 2
         Old   New
       <int> <int>
     1     1     1
     2    NA     1
     3    NA     1
     4    NA     1
     5    -1    -1
     6    NA    NA
     7    NA    NA
     8     1     1
     9    NA     1
    10    NA     1
    

    I think SO this question could also be helpful.