summarize to vector output

一世执手 提交于 2021-01-27 06:18:06

问题


Let's say I have the following (simplified) tibble containing a group and values in vectors:

set.seed(1)
(tb_vec <- tibble(group = factor(rep(c("A","B"), c(2,3))),
             values = replicate(5, sample(3), simplify = FALSE)))
# A tibble: 5 x 2
  group values   
  <fct> <list>   
1 A     <int [3]>
2 A     <int [3]>
3 B     <int [3]>
4 B     <int [3]>
5 B     <int [3]>

tb_vec[[1,2]]
[1] 1 3 2

I would like to summarize the values vectors per group by summing them (vectorized) and tried the following:

tb_vec %>% group_by(group) %>% 
  summarize(vec_sum = colSums(purrr::reduce(values, rbind)))

Error: Column vec_sum must be length 1 (a summary value), not 3

The error surprises me, because tibbles (the output format) can contain vectors as well.

My expected output would be the following summarized tibble:

# A tibble: 2 x 2
  group vec_sum  
  <fct> <list>   
1 A     <dbl [3]>
2 B     <dbl [3]>

Is there a tidyverse solution accommodate the vector output of summarize? I want to avoid splitting the tibble, because then I loose the factor.


回答1:


You just need to add list(.) within summarise in your solution, in order to be able to have a column with 2 elements, where each element is a vector of 3 values:

library(tidyverse)

set.seed(1)
(tb_vec <- tibble(group = factor(rep(c("A","B"), c(2,3))),
                  values = replicate(5, sample(3), simplify = FALSE)))

tb_vec %>% 
  group_by(group) %>%                              
  summarize(vec_sum = list(colSums(purrr::reduce(values, rbind)))) -> res

res$vec_sum

# [[1]]
# [1] 2 4 6
# 
# [[2]]
# [1] 6 5 7


来源:https://stackoverflow.com/questions/56957399/summarize-to-vector-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!