Export both Image and Data from R to an Excel spreadsheet

后端 未结 3 1940
南笙
南笙 2021-01-13 06:15

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()
         


        
3条回答
  •  无人及你
    2021-01-13 06:41

    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'))
    

提交回复
热议问题