Home > OS >  Convert a one-row table to data.frame
Convert a one-row table to data.frame

Time:04-03

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

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

Is there an easier way?

CodePudding user response:

Or another option is to use rbind with data.frame:

data.frame(rbind(ta), check.names = FALSE)

#   0 2 4 5
#ta 1 3 4 2

CodePudding user response:

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"

CodePudding user response:

Here is a dplyr solution:

library(dplyr)

df <- as_tibble(bind_rows(ta))
# A tibble: 1 × 4
  `0`     `2`     `4`     `5`    
  <table> <table> <table> <table>
1 1       3       4       2   
  • Related