如何将表格转换为数据框 [英] How to convert a table to a data frame

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

问题描述

我在 R 中有一个表,其中包含 str() :

I have a table in R that has str() of this:

 table [1:3, 1:4] 0.166 0.319 0.457 0.261 0.248 ...
 - attr(*, "dimnames")=List of 2
  ..$ x: chr [1:3] "Metro >=1 million" "Metro <1 million" "Non-Metro Counties"
  ..$ y: chr [1:4] "q1" "q2" "q3" "q4"

当我打印它时看起来像这样:

And looks like this when I print it:

                    y
x                           q1        q2        q3        q4
  Metro >=1 million  0.1663567 0.2612212 0.2670441 0.3053781
  Metro <1 million   0.3192857 0.2480012 0.2341030 0.1986102
  Non-Metro Counties 0.4570341 0.2044960 0.2121102 0.1263597

我想去掉 xy 并将其转换为与上面看起来完全相同的数据框(三行四列),但没有 xy.如果我使用 as.data.frame(mytable),我会得到这个:

I want to get rid of the x and y and convert it to a data frame that looks exactly the same as the above (three rows, four columns), but without the x or y. If I use as.data.frame(mytable), instead I get this:

                    x  y      Freq
1   Metro >=1 million q1 0.1663567
2    Metro <1 million q1 0.3192857
3  Non-Metro Counties q1 0.4570341
4   Metro >=1 million q2 0.2612212
5    Metro <1 million q2 0.2480012
6  Non-Metro Counties q2 0.2044960
7   Metro >=1 million q3 0.2670441
8    Metro <1 million q3 0.2341030
9  Non-Metro Counties q3 0.2121102
10  Metro >=1 million q4 0.3053781
11   Metro <1 million q4 0.1986102
12 Non-Metro Counties q4 0.1263597

我可能从根本上不理解表格与数据框的关系.

I probably fundamentally do not understand how tables relate to data frames.

推荐答案

我已经想通了:

as.data.frame.matrix(mytable) 

做我需要的——显然,表格需要以某种方式转换为矩阵,以便适当地转换为数据框.我找到了有关此 as.data.frame 的更多详细信息计算生态学博客中列联表的 .matrix() 函数.

does what I need -- apparently, the table needs to somehow be converted to a matrix in order to be appropriately translated into a data frame. I found more details on this as.data.frame.matrix() function for contingency tables at the Computational Ecology blog.

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

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