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
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?
CodePudding user response:
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)