Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

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

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.

1 Answer

0 votes
by

To turn a table into a data frame keeping the original structure we use as.data.frame.matrix

function,  as coercion of the table object into a data frame using as.data.frame function, puts each factor of the contingency table into its own column along with the frequency, not allowing its original structure to stay intact.

A contingency table is a display format used to analyze and record the relationship between two categorical variables. It will show the number of times each combination of the variables appear.

For example:

data(mtcars)

mytable <- table(cyl = mtcars$cyl, gear = mtcars$gear)

Contingency Table

as.data.frame(mytable)

  cyl gear Freq

1   4 3    1

2   6 3    2

3   8 3   12

4   4 4    8

5   6 4    4

6   8 4    0

7   4 5    2

8   6 5    1

9   8 5    2

Original Table to Data Frame

mytable <- as.data.frame.matrix(mytable)

mytable

   3 4 5

4  1 8 2

6  2 4 1

8 12 0 2

 str(mytable)

'data.frame': 3 obs. of  3 variables:

 $ 3: int  1 2 12

 $ 4: int  8 4 0

 $ 5: int  2 1 2

Browse Categories

...