简体   繁体   English

将图像和数据从 R 导出到 Excel 电子表格

[英]Export both Image and Data from R to an Excel spreadsheet

It is simple to print an image and save it on disk just:打印图像并将其保存在磁盘上很简单:

fit <- lm(some ~ model)

png(filename="your/file/location/name.png")
plot(fit)
dev.off()

Write some data to a excel spreadsheet just将一些数据写入excel电子表格

write.csv(rnorm(10),"some file",sep=",")

My question is how would one redirect both the above in to a spreadsheet.我的问题是如何将上述内容重定向到电子表格中。 Another word, output a graph paired withs some image/plot on to a excel workbook?换句话说,将与一些图像/绘图配对的图形输出到 Excel 工作簿?

Thanks,谢谢,

I would use the xlsx package.我会使用xlsx包。 Check out the addPicture function and the addDataFrame function.查看addPicture函数和addDataFrame函数。 I found this package fairly easy to work with.我发现这个包很容易使用。

You can do the same thing with the insertImage function and using the openxlsx package.您可以使用insertImage函数并使用openxlsx包执行相同的操作。

I've copied the example from above, but using the openxlsx package instead:我从上面复制了这个例子,但是使用了 openxlsx 包:

# Setup
x <- c('tidyverse', 'openxlsx')
sapply(X=x, FUN = require, character.only = TRUE)

# Create graph---------
dcs <- ggplot(mtcars) +
  geom_point(aes(cyl, disp))

# Export Pic -----------
pic_path <- "C:/home/dcs.jpeg"
png(filename = pic_path)
plot(dcs)
dev.off()

# Add to a new work book -------------
wb <- openxlsx::createWorkbook()
addWorksheet(wb, "Plots")
insertImage(wb, "Plots", pic_path)
openxlsx::saveWorkbook(wb,
                       "~/example.xlsx")

# Kill pic
unlink(pic_path)

Just to add an example about the xlsx package, as far as i can tell it requires you to first save the picture, then import it to the xlsx file, see a reproducible example of exporting to an existing book below:只是添加一个关于 xlsx 包的示例,据我所知,它要求您首先保存图片,然后将其导入 xlsx 文件,请参阅下面的导出到现有书籍的可重现示例:

# Setup
x <- c('tidyverse', 'rJava', 'xlsxjars', 'xlsx')
sapply(X=x, FUN = require, character.only = TRUE)

# Create graph---------
dcs <- ggplot(mtcars) +
  geom_point(aes(cyl, disp))

# Export Pic -----------
pic_path <- "C:/home/dcs.jpeg"
png(filename = pic_path)
plot(dcs)
dev.off()

# Add to existing book -------------
xl_path <- "C:/home/a.xlsx"

wb <- loadWorkbook(xl_path)

ws <- getSheets(wb)["Summary"][[1]]

addPicture(file = pic_path, sheet = ws)

saveWorkbook(wb, xl_path)

# Kill pic
unlink(pic_path)

#Then write some data
write.xlsx(as.data.frame(output), xl_path, sheetName = 'data'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM