如何将摘要输出转换为数据框? [英] How to convert summary output to a data frame?

查看:71
本文介绍了如何将摘要输出转换为数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总结了由ID组成的数据框的一列(称为DATA),因此我获得了给定列中每个ID的总数。我想将其转换为另一个数据框(称为TOTALNUM),所以有两列。第一列是ID本身,第二列是每个ID的总数。

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?

样本数据:

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

谢谢!

推荐答案

使用这种方法,您可以利用以下事实: summary 返回一个计数向量,每个值的名称为 ids

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

或者-这种方法更简单-您可以根据 ids 创建频率表,然后将其转换为数据框:

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

这篇关于如何将摘要输出转换为数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆