2

Under certain conditions, R generates data frames that contain matrices as elements. This requires some determination to do by hand, but happens e.g. with the results of an aggregate() call where the aggregation function returns multiple values:

set.seed(101)
d0 <- data.frame(g=factor(rep(1:2,each=20)), x=rnorm(20))
d1 <- aggregate(x~g, data=d0, FUN=function(x) c(m=mean(x), s=sd(x)))
str(d1)
## 'data.frame':    2 obs. of  2 variables:
##  $ g: Factor w/ 2 levels "1","2": 1 2
##  $ x: num [1:2, 1:2] -0.0973 -0.0973 0.8668 0.8668
##   ..- attr(*, "dimnames")=List of 2
##   .. ..$ : NULL
##  .. ..$ : chr  "m" "s"

This makes a certain amount of sense, but can make trouble for downstream processing code (for example, ggplot2 doesn't like it). The printed representation can also be confusing if you don't know what you're looking at:

d1
##   g         x.m         x.s
## 1 1 -0.09731741  0.86678436
## 2 2 -0.09731741  0.86678436

I'm looking for a relatively simple way to collapse this object to a regular three-column data frame (either with names g, m, s, or with names g, x.m, x.s ...).

I know this problem won't arise with tidyverse (group_by + summarise), but am looking for a base-R solution.

0

0

Browse other questions tagged or ask your own question.