MatthewR
MatthewR

Reputation: 2770

keep dimensions of table when converting to a data.frame

I am using the xlsx package to write tables to an excel file. I want to use the xlsx package so I can write multiple tabs. xlsx converts the tables into data.frames and in so doing changes the dimensions.

b <- sample( c("bob", "mark", "joanna"), 100, replace=TRUE) 
a <- c( sample( 1:5, 100, replace=TRUE) ) 
a <- data.frame( a , b)

d <- table( a$a , a$b )

e <- data.frame(d)

print (e)
print(d)

see how the dimensions of d are different than e. Is there an easy way to keep the dimensions of d when converting? I looked around in previous questions and didn't see anyone tackle this.

Upvotes: 2

Views: 581

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193667

You're probably looking for as.data.frame.matrix:

> as.data.frame.matrix(d)
  bob joanna mark
1   1      7    9
2  10      7    4
3   4      6   14
4   6      8   11
5   5      7    1

There are different "methods" that are used when calling data.frame on different types of inputs. Run methods("as.data.frame") to see a list of those. Looking at that list, you would see that there is a specific method for tables. You can view that code by just typing as.data.frame.table. If you treat your table as a matrix, you get the behavior I think you're expecting.

Upvotes: 2

Related Questions