As simple example I want to calculate the matrix product of two vectors.
a <- tibble(n=c("A", "B"), y=c(10,20))
b <- tibble(x=c(5, 15))
res <- a %>%
mutate(rotated = map2(y, b, ~ .x %*% .y)) %>%
unnest(rotated)
Everything seems to be fine, but I would expect, that after unnesting, the tibble should be 2x4 tibble, but I have still a 2x3 tibble, e.g.
n y rotated[,1] [,2]
<chr> <dbl> <dbl> <dbl>
1 A 10 50 150
2 B 20 100 300
so after checking
res$rotated
I'll get the error
Error in if (nchar(current) > nchars) { :
missing value where TRUE/FALSE needed
Also the answer in
How to unnest tibbles within a tibble?
with bind_cols
doesn't solve the problem.
Thanks for any hints
Probably you can try unnest_wider
like below
a %>%
mutate(rotated = as.data.frame(do.call(rbind, map2(y, b, ~ .x %*% .y)))) %>%
unnest_wider(rotated)
or
a %>%
reframe(rotated = as.data.frame(map2(y, b, ~ .x %*% .y)), .by = c(n, y)) %>%
unnest_wider(rotated)
which gives
# A tibble: 2 × 4
n y X1 X2
<chr> <dbl> <dbl> <dbl>
1 A 10 50 150
2 B 20 100 300