user974887
user974887

Reputation: 2499

Rownames to column in table not working, converts to list or as.data.frame introduces extra rows

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

Upvotes: 1

Views: 2536

Answers (1)

Prem
Prem

Reputation: 11985

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

Upvotes: 1

Related Questions