Home > Software design >  Complete / fill sorted integer sequence with NAs
Complete / fill sorted integer sequence with NAs

Time:09-09

Consider this sorted vector:

x <- c(3, 4, 6, 8, 9, 10, 18)

Is there an easy way to complete the sequence with NAs, i.e. get:

#[1] 3  4 NA  6 NA  8  9 10 NA NA NA NA NA NA NA 18

CodePudding user response:

You can create the full sequence and add NAs on unmatched numbers:

s <- seq(min(x), max(x))
s[!s %in% x] <- NA

#[1]  3  4 NA  6 NA  8  9 10 NA NA NA NA NA NA NA 18

You could create even create functions that take as input the vector, a minimum and maximum and add NAs to non matching numbers:

fill_seq <- 
  function(x, min = NULL, max = NULL, by = 1){
    min = if(is.null(min)) min(x) else min
    max = if(is.null(max)) max(x) else max
   
    s <- seq(min, max, by = by)
    s[!s %in% x] <- NA
    s
  }

Examples:

fill_seq(x)
# [1]  3  4 NA  6 NA  8  9 10 NA NA NA NA NA NA NA 18

fill_seq(x, min = 1, max = 20)
#  [1] NA NA  3  4 NA  6 NA  8  9 10 NA NA NA NA NA NA NA 18 NA NA

fill_seq(x, by = 0.5)
# [1]  3 NA  4 NA NA NA  6 NA NA NA  8 NA  9 NA 10 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA 18

CodePudding user response:

Using replace.

replace(array(dim=max(x)), x, x)[-seq_len(min(x) - 1)]
# [1]  3  4 NA  6 NA  8  9 10 NA NA NA NA NA NA NA 18
  • Related