This is indeed strange, and I haven't quite figured it out. Some investigations, though…
Without a replacement value supplied, complete()
introduces NAs. From the example in the tidyr docs:
library(tidyverse)
df <- tibble(
group = c(1:2, 1),
item_id = c(1:2, 2),
item_name = c("a", "b", "b"),
value1 = 1:3,
value2 = 4:6
)
df %>% complete(group, nesting(item_id, item_name))
#> # A tibble: 4 x 5
#> group item_id item_name value1 value2
#> <dbl> <dbl> <chr> <int> <int>
#> 1 1 1 a 1 4
#> 2 1 2 b 3 6
#> 3 2 1 a NA NA
#> 4 2 2 b 2 5
Created on 2018-10-17 by the reprex package (v0.2.1.9000)
The fill
argument for complete()
is described:
A named list that for each variable supplies a single value to use instead of NA
for missing combinations.
The output for the full_seq()
alone is just;
tidyr::full_seq(c(0.012, 0.013, 0.014, 0.012, 0.013, 0.014), 0.001, tol = 1e-03)
#> [1] 0.012 0.013 0.014
So the output would be the same as your initial dat
:
library(tidyverse)
dat <- tibble(group = c("A", "A", "A", "B", "B", "B"),
beta = c(0.012, 0.013, 0.014, 0.012, 0.013, 0.014),
D = c(0.174, 0.16, 0.158, 0.204, 0.182, 0.164))
dat %>% complete(nesting(group), beta = c(0.012, 0.013, 0.014))
#> # A tibble: 6 x 3
#> group beta D
#> <chr> <dbl> <dbl>
#> 1 A 0.012 0.174
#> 2 A 0.013 0.16
#> 3 A 0.014 0.158
#> 4 B 0.012 0.204
#> 5 B 0.013 0.182
#> 6 B 0.014 0.164
Since complete is just;
…a wrapper around expand()
, dplyr::left_join()
You should be able to piece it back together by, essentially, using the original table to lookup the value (using a left join), but that seems like a rather roundabout way of approaching things, and it still loses the 0.130 values…
library(tidyverse)
dat <- tibble(group = as.factor(c("A", "A", "A", "B", "B", "B")),
beta = c(0.012, 0.013, 0.014, 0.012, 0.013, 0.014),
D = c(0.174, 0.160, 0.158, 0.204, 0.182, 0.164))
dat
#> # A tibble: 6 x 3
#> group beta D
#> <fct> <dbl> <dbl>
#> 1 A 0.012 0.174
#> 2 A 0.013 0.16
#> 3 A 0.014 0.158
#> 4 B 0.012 0.204
#> 5 B 0.013 0.182
#> 6 B 0.014 0.164
dat %>% complete(nesting(group), beta = full_seq(beta, 0.001, tol = 1e-03))
#> # A tibble: 6 x 3
#> group beta D
#> <fct> <dbl> <dbl>
#> 1 A 0.012 0.174
#> 2 A 0.013 NA
#> 3 A 0.014 0.158
#> 4 B 0.012 0.204
#> 5 B 0.013 NA
#> 6 B 0.014 0.164
dat2 <- dat %>%
expand(nesting(group), beta = full_seq(beta, 0.0001, tol = 1e-04))
dat3 <- dat2 %>%
left_join(dat, by = c("group", "beta"))
head(dat3, n = 12)
#> # A tibble: 12 x 3
#> group beta D
#> <fct> <dbl> <dbl>
#> 1 A 0.012 0.174
#> 2 A 0.0121 NA
#> 3 A 0.0122 NA
#> 4 A 0.0123 NA
#> 5 A 0.0124 NA
#> 6 A 0.0125 NA
#> 7 A 0.0126 NA
#> 8 A 0.0127 NA
#> 9 A 0.0128 NA
#> 10 A 0.0129 NA
#> 11 A 0.013 NA
#> 12 A 0.0131 NA
Created on 2018-10-17 by the reprex package (v0.2.1.9000)
n.b. if you run that last part, you'll see the 0.120 and 0.140 join works fine, I just didn't want to print that whole sequence