1

My data is a count table of categorical variables from a larger data frame. My goal is to plot the number of instances of alive/dead for each treatment in that data frame.

The dataframe looks like this:

  Treatment Plate Sex                 Days Status
1          1     1   U                  NA   Dead
2          1     1   U                  NA   Dead
3          1     1   U                  NA   Dead
4          1     1   U                  NA   Alive
5          1     1   U                  NA   Dead
6          1     1   U                  NA   Dead

The data table looks like this:

table(Subset$Treatment, Subset$Status)

           Dead Still_kicking
  1         144             0
  3         141             3
  7         144             0
  10        105            39
  13         69             3
  Control    12            60
  Control2    2            70

I want the row names to column (prefer a one-liner). When I try to add the column I get this:

> Status$names <- rownames(Status)
Warning message:
In Status$names <- rownames(Status) : Coercing LHS to a list
> Status
[[1]]
[1] 144

[[2]]
[1] 141

[[3]]
[1] 144

If I convert to a data frame I get extra rows:

> Status <- data.frame(Status)
> Status
       Var1          Var2 Freq
1         1          Dead  144
2         3          Dead  141
3         7          Dead  144
4        10          Dead  105
5        13          Dead   69
6   Control          Dead   12
7  Control2          Dead    2
8         1 Still_kicking    0
9         3 Still_kicking    3
10        7 Still_kicking    0
11       10 Still_kicking   39
12       13 Still_kicking    3
13  Control Still_kicking   60
14 Control2 Still_kicking   70
user974887
  • 2,309
  • 3
  • 17
  • 18
  • 1
    One thing you need to note is a table is a restructured arranged dataframe. eg so the rownames are not observational units but rather variables as well – Onyambu Feb 09 '18 at 19:09
  • you can also use `as.data.frame.matrix(Status)` this will create a data.frame exactly looking like your table. See https://stackoverflow.com/questions/10758961/how-to-convert-a-table-to-a-data-frame – Linus Feb 09 '18 at 19:23

1 Answers1

1

You seem to be looking for unclass.

In below example I have used mtcars dataset to convert table(mtcars$cyl, mtcars$am)

     0  1
  4  3  8
  6  4  3
  8 12  2

into dataframe format.

tibble::rownames_to_column can be used to add rownames as the first column.

library(tibble)
rownames_to_column(data.frame(unclass(table(mtcars$cyl, mtcars$am))), 
                   "rownames_col")

Output is:

  rownames_col X0 X1
1            4  3  8
2            6  4  3
3            8 12  2
Prem
  • 11,775
  • 1
  • 19
  • 33