Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert a one-row table to data.frame

Consider a table:

ta <- structure(c(`0` = 1L, `2` = 3L, `4` = 4L, `5` = 2L), .Dim = 4L, .Dimnames = list(
    x = c("0", "2", "4", "5")), class = "table")

#> ta
# x
# 0 2 4 5 
# 1 3 4 2

With simple table, the conventional way (as.data.frame.matrix) does not seem to work:

> as.data.frame.matrix(ta) 
Error in d[[2L]] : subscript out of bounds

So, is there an easy way to convert a table with one row to a data frame? So far, the only way I came up with is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

as.data.frame(t(as.data.frame.array(ta)))
   0 2 4 5
ta 1 3 4 2

Is there an easier way?

>Solution :

It is a 1d table, so convert to list

as.data.frame.list(ta, check.names = FALSE)
  0 2 4 5
1 1 3 4 2

With the OP’s approach the as.data.frame.matrix can work if we do the transpose

as.data.frame.matrix(t(ta))

as the difference is in the addition of a second dimension

> str(ta)
 'table' int [1:4(1d)] 1 3 4 2
 - attr(*, "dimnames")=List of 1
  ..$ x: chr [1:4] "0" "2" "4" "5"
> str(t(ta))
 'table' int [1, 1:4] 1 3 4 2
 - attr(*, "dimnames")=List of 2
  ..$  : NULL
  ..$ x: chr [1:4] "0" "2" "4" "5"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading