作为一个简单的例子,我想计算两个向量的矩阵积。
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)
一切似乎都很好,但我预计,在取消发送后,tibble应该是2x4 tibble,但我仍然有一个2x3 tibble,例如。
n y rotated[,1] [,2] <chr> <dbl> <dbl> <dbl> 1 A 10 50 150 2 B 20 100 300
所以检查后
res$rotated
我会得到错误
Error in if (nchar(current) > nchars) { : missing value where TRUE/FALSE needed
答案也在
How to unnest tibbles within a tibble?
具有 bind_cols 并不能解决问题。
bind_cols
谢谢你的任何提示
也许你可以试试 unnest_wider 如下图所示
unnest_wider
a %>% mutate(rotated = as.data.frame(do.call(rbind, map2(y, b, ~ .x %*% .y)))) %>% unnest_wider(rotated)
或
a %>% reframe(rotated = as.data.frame(map2(y, b, ~ .x %*% .y)), .by = c(n, y)) %>% unnest_wider(rotated)
这给了
# A tibble: 2 Ã 4 n y X1 X2 <chr> <dbl> <dbl> <dbl> 1 A 10 50 150 2 B 20 100 300