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()
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:
# 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'))