Export both Image and Data from R to an Excel spreadsheet

后端 未结 3 1931
南笙
南笙 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'))
    
    0 讨论(0)
  • 2021-01-13 06:50

    I would use the xlsx package. Check out the addPicture function and the addDataFrame function. I found this package fairly easy to work with.

    0 讨论(0)
  • 2021-01-13 07:05

    You can do the same thing with the insertImage function and using the openxlsx package.

    I've copied the example from above, but using the openxlsx package instead:

    # 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)
    
    0 讨论(0)
提交回复
热议问题