Damien
Damien

Reputation: 392

How to write a table from R into Excel

I am trying to write a table from R into Excel. Here is some sample code:

library(XLConnect)
wb     <- loadWorkbook("C:\\Users\\Bob\\Desktop\\Example.xls", create=TRUE)
output <- as.table(output)
createSheet(wb, name="Worksheet 1")
writeWorksheet(wb, output, sheet="Worksheet 1")
saveWorkbook(wb)

But it seems that the writeWorksheet function converts the table into a dataframe. This makes the data look messy and unformatted. I want the table structure to be preserved. How would I modify the above code?

Upvotes: 1

Views: 2451

Answers (1)

joran
joran

Reputation: 173517

The issue here is that writeWorksheet converts the table object to a data frame. The way that happens is that R will basically "melt" it into long format, whereas a table object is typically printed to the console in "wide" format.

It is a bit of a nuisance, but you generally have to manually convert the table into a data frame that matches the format you're after. An example:

library(reshape2)
tbl <- with(mtcars,table(cyl,gear))
> tbl
   gear
cyl  3  4  5
  4  1  8  2
  6  2  4  1
  8 12  0  2
> as.data.frame(tbl)
  cyl gear Freq
1   4    3    1
2   6    3    2
3   8    3   12
4   4    4    8
5   6    4    4
6   8    4    0
7   4    5    2
8   6    5    1
9   8    5    2
> tbl_df <- as.data.frame(tbl)
> final <- dcast(tbl_df,cyl~gear,value.var = "Freq")
> final
  cyl  3 4 5
1   4  1 8 2
2   6  2 4 1
3   8 12 0 2
> class(final)
[1] "data.frame"

Then you should be able to write that data frame to the Excel worksheet with no problem.

Upvotes: 1

Related Questions