Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert summary output to a data frame?

Tags:

dataframe

r

I have summarized a column of a data frame (call this DATA) that consists of IDs so I get the total number of each ID in the given column. I'd like to convert this to another data frame (call this TOTALNUM), so I have two columns. The first column is the ID itself and the second column is the total number of each ID. Is this possible?

Sample data:

ids <- c(1,2,3,4,5,1,2,3,1,5,1,4,2,2,2)
info <- c("A","B","C","A","B","C","A","B","C","A","B","C","A","B","C")
DATA <- data.frame(ids, info)
DATA$ids <- as.factor(DATA$ids)

What I would like to put in a data frame: Top row would be the first column in a new data frame. Second row would be the second column in a new data frame.

summary(DATA$ids)

This is what I would like the data frame to look like:

ids    nums
1      4
2      5
3      2
4      2
5      2

Thanks!!

like image 716
Sheila Avatar asked Jun 21 '13 20:06

Sheila


1 Answers

With your approach, you can take advantage of the fact that summary returns a vector of counts, with names for each value of ids:

> my.summary <- summary(DATA$ids)
> data.frame(ids=names(my.summary), nums=my.summary)
  ids nums
1   1    4
2   2    5
3   3    2
4   4    2
5   5    2

Or--and this approach is more straightforward--you can create a frequency table based on ids and then convert that to a data frame:

> as.data.frame(table(ids), responseName="nums")
  ids nums
1   1    4
2   2    5
3   3    2
4   4    2
5   5    2
like image 166
Peyton Avatar answered Sep 27 '22 19:09

Peyton