R. Martin
R. Martin

Reputation: 109

Split a dataframe within a dataframe to columns in the same dataframe

I've created a dataframe as a result of a mongolite $aggregate method. I aggregated on two columns in the query, so now my results DF has a dataframe within a dataframe. How do I split out these two columns, year and month, into their own columns within the "outer" dataframe partOneCrimeDF? As a side note, when I did the mongolite aggregate on a single column, the dataframe within the dataframe was just one column, so it was easy to split out. Here's a display of my data:

> str(partOneCrimeDF)
'data.frame':   38 obs. of  2 variables:
 $ _id  :'data.frame':  38 obs. of  2 variables:
  ..$ year : int  2015 2015 2015 2015 2015 2015 2015 2015 2014 2014 ...
  ..$ month: int  8 7 6 5 4 3 2 1 12 11 ...
 $ count: int  457 1733 1632 1674 1554 1399 955 1365 1740 1666 ...

> dput(partOneCrimeDF)
structure(list(`_id` = structure(list(year = c(2015L, 2015L, 
2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2014L, 2014L, 2014L, 
2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 
2013L, 2013L, 2013L, 2013L, 2013L, 2013L, 2013L, 2013L, 2013L, 
2013L, 2013L, 2013L, 2012L, 2012L, 2012L, 2012L, 2012L, 2012L
), month = c(8L, 7L, 6L, 5L, 4L, 3L, 2L, 1L, 12L, 11L, 10L, 9L, 
8L, 7L, 6L, 5L, 4L, 3L, 2L, 1L, 12L, 11L, 10L, 9L, 8L, 7L, 6L, 
5L, 4L, 3L, 2L, 1L, 12L, 11L, 10L, 9L, 8L, 7L)), .Names = c("year", 
"month"), class = "data.frame", row.names = c(NA, 38L)), count = c(457L, 
1733L, 1632L, 1674L, 1554L, 1399L, 955L, 1365L, 1740L, 1666L, 
1879L, 1835L, 1938L, 2000L, 1934L, 1860L, 1648L, 1575L, 1289L, 
1764L, 1763L, 1859L, 1908L, 1873L, 2005L, 2191L, 1971L, 1920L, 
1673L, 1618L, 1246L, 1674L, 1898L, 1867L, 1947L, 2148L, 2106L, 
1697L)), .Names = c("_id", "count"), class = "data.frame", row.names = c(NA, 
38L))

Upvotes: 1

Views: 111

Answers (1)

akrun
akrun

Reputation: 886948

We can use do.call with data.frame

newDF <- do.call(data.frame, partOneCrimeDF)

Upvotes: 1

Related Questions