How to convert summary output to a data frame?

2020-08-27 10:47发布

问题:

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!!

回答1:

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


标签: r dataframe