1

Here is what I'm trying to accomplish

> table(mtcars$cyl)

 4  6  8 
11  7 14 

And I need it in this format,

mtcars_table <- data.frame(
  "4" = c(11),
  "6" = c(6),
  "8" = c(14))

> print(mtcars_table)
  X4 X6 X8
1 11  6 14

I pretty much need the categorical variables as my columns and the counts as my row. If there is a dplyr way to this easier i'm open to it as well.

s_baldur
  • 29,441
  • 4
  • 36
  • 69
RL_Pug
  • 697
  • 7
  • 30

2 Answers2

4

Try with this:

#Code
mytable <- data.frame(rbind(table(mtcars$cyl)))

Output:

  X4 X6 X8
1 11  7 14
Duck
  • 39,058
  • 13
  • 42
  • 84
1
# unclass() + t()
as.data.frame(t(unclass(table(mtcars$cyl))))
#    4 6  8
# 1 11 7 14

# as.list()
as.data.frame(as.list(table(mtcars$cyl)))
  X4 X6 X8
1 11  7 14

# Super fast
data.table::setDF(as.list(table(mtcars$cyl)))[]
s_baldur
  • 29,441
  • 4
  • 36
  • 69