dmvianna
dmvianna

Reputation: 15718

From table to data.frame

I have a table that looks like:

dat = data.frame(expand.grid(x = 1:10, y = 1:10),
             z = sample(LETTERS[1:3], size = 100, replace = TRUE))
tabl <- with(dat, table(z, y))

tabl
   y
z   1 2 3 4 5 6 7 8 9 10
  A 5 3 1 1 3 6 3 7 2  4
  B 4 5 3 6 5 1 3 1 4  4
  C 1 2 6 3 2 3 4 2 4  2

Now how do I transform it into a data.frame that looks like

    1 2 3 4 5 6 7 8 9 10
  A 5 3 1 1 3 6 3 7 2  4
  B 4 5 3 6 5 1 3 1 4  4
  C 1 2 6 3 2 3 4 2 4  2

Upvotes: 0

Views: 116

Answers (1)

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162321

Here are a couple of options. The reason as.data.frame(tabl) doesn't work is that it dispatches to the S3 method as.data.frame.table() which does something useful but different from what you want.

as.data.frame.matrix(tabl)
#   1 2 3 4 5 6 7 8 9 10
# A 5 4 3 1 1 3 3 2 6  2
# B 1 4 3 4 5 3 4 4 3  3
# C 4 2 4 5 4 4 3 4 1  5

## This will also work
as.data.frame(unclass(tabl))

Upvotes: 2

Related Questions