[英]sum list-column of matrices (from nested data.frame) using R, dplyr
我有一個分組的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
如何將列表列 m 中的矩陣添加到單個矩陣中?
我嘗試使用
d_by %>% summarise(sum(m))
但收到錯誤消息:
Error in sum(m) : invalid 'type' (list) of argument
您可以對任意數量的矩陣使用reduce
purrr::reduce(d_by$m, `+`)
或在base R
Reduce(`+`, d_by$m)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.