[英]How to write a table from R into Excel
I am trying to write a table from R into Excel. 我试图将表格从R写入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. 但是似乎
writeWorksheet
函数将表转换为数据writeWorksheet
。 This makes the data look messy and unformatted. 这使数据看起来混乱且未格式化。 I want the table structure to be preserved.
我希望保留表结构。 How would I modify the above code?
我将如何修改以上代码?
The issue here is that writeWorksheet
converts the table object to a data frame. 这里的问题是
writeWorksheet
将表对象转换为数据框。 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. 发生的方式是R基本上将其“熔化”为长格式,而表对象通常以“宽”格式打印到控制台。
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. 然后,您应该可以毫无问题地将该数据框写入Excel工作表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.