如何将表转换为数据框

我在R中有一张桌子有str()这个:


 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"

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


                    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

我想摆脱x和y并将其转换成数据帧,看起来完全一样,上面的(三排,四列),但没有x或y。如果我使用as.data.frame(mytable),我会得到这个:


                    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

我可能从根本上不了解表与数据帧之间的关系。


MYYA
浏览 560回答 3
3回答

Qyouu

我已经知道了:as.data.frame.matrix(mytable)&nbsp;满足我的需要-显然,该表需要以某种方式转换为矩阵,以便适当地转换为数据帧。我在Computational Ecology博客上发现了有关列联表as.data.frame.matrix()函数的更多详细信息。

PIPIONE

尽管在这种情况下结果会有所不同,因为列名是数字,但我使用的另一种方法是data.frame(rbind(mytable))。使用@XX中的示例:> freq_t = table(cyl = mtcars$cyl, gear = mtcars$gear)> freq_t&nbsp; &nbsp;gearcyl&nbsp; 3&nbsp; 4&nbsp; 5&nbsp; 4&nbsp; 1&nbsp; 8&nbsp; 2&nbsp; 6&nbsp; 2&nbsp; 4&nbsp; 1&nbsp; 8 12&nbsp; 0&nbsp; 2> data.frame(rbind(freq_t))&nbsp; X3 X4 X54&nbsp; 1&nbsp; 8&nbsp; 26&nbsp; 2&nbsp; 4&nbsp; 18 12&nbsp; 0&nbsp; 2如果列名不是以数字开头,则不X会将其添加到它们的前面。

www说

简短的答案:使用as.data.frame.matrix(mytable)@Victor Van Hee建议的。长答案:as.data.frame(mytable)可能无法在table()函数生成的列联表上使用,即使is.matrix(your_table)return TRUE。它仍然会将您的表融为一体factor1 factor2 factori counts。例:> freq_t = table(cyl = mtcars$cyl, gear = mtcars$gear)> freq_t&nbsp; &nbsp;gearcyl&nbsp; 3&nbsp; 4&nbsp; 5&nbsp; 4&nbsp; 1&nbsp; 8&nbsp; 2&nbsp; 6&nbsp; 2&nbsp; 4&nbsp; 1&nbsp; 8 12&nbsp; 0&nbsp; 2> is.matrix(freq_t)[1] TRUE> as.data.frame(freq_t)&nbsp; cyl gear Freq1&nbsp; &nbsp;4&nbsp; &nbsp; 3&nbsp; &nbsp; 12&nbsp; &nbsp;6&nbsp; &nbsp; 3&nbsp; &nbsp; 23&nbsp; &nbsp;8&nbsp; &nbsp; 3&nbsp; &nbsp;124&nbsp; &nbsp;4&nbsp; &nbsp; 4&nbsp; &nbsp; 85&nbsp; &nbsp;6&nbsp; &nbsp; 4&nbsp; &nbsp; 46&nbsp; &nbsp;8&nbsp; &nbsp; 4&nbsp; &nbsp; 07&nbsp; &nbsp;4&nbsp; &nbsp; 5&nbsp; &nbsp; 28&nbsp; &nbsp;6&nbsp; &nbsp; 5&nbsp; &nbsp; 19&nbsp; &nbsp;8&nbsp; &nbsp; 5&nbsp; &nbsp; 2> as.data.frame.matrix(freq_t)&nbsp; &nbsp;3 4 54&nbsp; 1 8 26&nbsp; 2 4 18 12 0 2
打开App,查看更多内容
随时随地看视频慕课网APP