简体   繁体   English

使用 R、dplyr 矩阵的总和列表列(来自嵌套的 data.frame)

[英]sum list-column of matrices (from nested data.frame) using R, dplyr

I have a grouped data.frame , with a column m that contains 2x2 matrices, as in this example:我有一个分组的data.frame ,其中m列包含 2x2 矩阵,如本例所示:

library(tidyverse)
d <- data.frame(g=c(1,1,2,2),x1=c(1,1,1,1),x2=c(1,1,1,1))
d_by <- d  %>%  group_by(g) %>% nest %>% 
  mutate(m = map(data,data.matrix))
d_by$m %>% str

How can I add the matrices in list-column m into a single matrix?如何将列表列 m 中的矩阵添加到单个矩阵中?

I tried using我尝试使用

d_by %>% summarise(sum(m))

But got the error message:但收到错误消息:

Error in sum(m) : invalid 'type' (list) of argument

You can use reduce for an arbitrary number of matrices您可以对任意数量的矩阵使用reduce

purrr::reduce(d_by$m, `+`)

Or in base R或在base R

Reduce(`+`, d_by$m)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM