Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Complete vector of numbers

I have a vector that looks like this:

vector <- c(3.1, 5.3, 5.5)

and I want to fill in the missing numbers, resulting in:

1.0, 2.0, 3.1, 4.0, 5.1, 5.2, 5.3, 5.4, 5.5

or

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1.0, 2.0, 3.0, 3.1, 4.0, 5.0, 5.1, 5.2, 5.3, 5.4, 5.5

How can that be done?

>Solution :

library(purrr)

vector <- c(3.1, 5.3, 5.5)

vector %>%
  # add floating point numbers
  # e.g. 3.3 -> c(3.0, 3.1, 3.2, 3.3)
  keep(~ .x %% 1 != 0) %>%
  map(~ {
    a <- as.integer(.x)
    b <- (.x %% 1) * 10 - 1
    a + (seq(0, b) / 10)
  }) %>%
  simplify() %>%
  # add original values
  c(vector) %>%
  c(
    # add integers
    vector %>% as.integer() %>% max() %>% seq()
  ) %>%
  # tidy up
  sort() %>%
  unique()
#>  [1] 1.0 2.0 3.0 3.1 4.0 5.0 5.1 5.2 5.3 5.4 5.5

Created on 2021-12-08 by the reprex package (v2.0.1)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading