Exporting Histogram from R to Excel

人走茶凉 提交于 2019-12-22 18:00:58

问题


I have some data in R that I would like to represent as a histogram (actually, I'll have 6 histograms) and then export those graphs into an excel file. I have just been using the hist() function, but I'm also experimenting with ggplot2 functions. Every histogram has 10,000 pieces of data, so I can't just export the raw data and create the histograms in excel (I'm assuming that this would lead to a ridiculously sized excel file, which I don't want).

Is there any way I can export my graphs?


回答1:


The excel.link package is a wrapper to RDCOMClient.

The following example only worked for me in R 3.0.1 in the normal RGui (not RStudio).

# load package
require(excel.link)

# plot something
plot(cos)

# save graph to tmp file
cos.plot=current.graphics()

# add excel workbook
xl.workbook.add()

# add sheet to excel workbook
xl.sheet.add()

# put your graph starting at the top left in cell A1
xl[a1]=list("Cosine plotting",cos.plot,"End of cosine plotting")



回答2:


Another solution is to store the binned data into a data frame and export the data frame to excel via un CSV file or any other format.

> x  <- rnorm(1000)
> h  <- hist(x)
> h
$breaks
 [1] -3.5 -3.0 -2.5 -2.0 -1.5 -1.0 -0.5  0.0  0.5  1.0  1.5  2.0  2.5  3.0  3.5  4.0

$counts
 [1]   1   5  23  38 104 154 208 191 130  85  39  17   4   0   1

$density
 [1] 0.002 0.010 0.046 0.076 0.208 0.308 0.416 0.382 0.260 0.170 0.078 0.034 0.008 0.000 0.002

$mids
[1] -3.25 -2.75 -2.25 -1.75 -1.25 -0.75 -0.25  0.25  0.75  1.25  1.75  2.25  2.75  3.25  3.75

$xname
[1] "x"

$equidist
[1] TRUE

attr(,"class")
[1] "histogram"
> out  <- data.frame(mid = h$mids, counts = h$counts)
> write.table(out, file = "export.csv", row.names = FALSE, sep = ",")

Note that you can also export the density if you want.



来源:https://stackoverflow.com/questions/17948776/exporting-histogram-from-r-to-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!