如何用R建立powerpoint報告
本文將通過展示我們如何使用officer 來建立PowerPoint報表。
入門
讓我們從載入officer開始。
library(officer)
接下來,我們將使用read_pptx函式在R中建立PowerPoint物件。
pres <- read_pptx()
要新增一張幻燈片,我們使用add_slide函式。 我們將建立的第一張幻燈片是標題幻燈片。 我們在layout引數中指定幻燈片的型別。 這裡還有其他幾種可能,包括“標題和內容”,“空白”,“僅標題”,“比較”,“兩個內容”和“部分標題”。
其次,我們使用ph_with新增標題文字。
# add title slide pres <- add_slide(pres, layout = "Title Only", master = "Office Theme") # add Title text pres <- ph_with(pres, value = "My first presentation", location = ph_location_type(type = "title"))
接下來,讓我們新增另一張幻燈片。 這次我們將有一個標題和內容。
pres <- add_slide(pres, layout = "Title and Content", master = "Office Theme") pres <- ph_with(pres, value = "This is the second slide", location = ph_location_type(type = "title")) pres <- ph_with(pres, value = c("First line", "Second Line", "Third line"), location = ph_location_type(type = "body"))
如何新增表格
現在,如果我們要新增表怎麼辦? 讓我們建立一個示例資料框並將其新增到新幻燈片中。 同樣,我們將使用ph_with將內容(在這種情況下為資料框)新增到新幻燈片中。 這次我們只需要將value引數設定為等於我們的資料框物件。
# create sample data frame frame <- data.frame(a = 1:10, b = 11:20, c = 21:30) # create slide to hold table pres <- add_slide(pres, layout = "Title and Content", master = "Office Theme") pres <- ph_with(pres, value = "Table Example", location = ph_location_type(type = "title")) # add data frame to PowerPoint slide pres <- ph_with(pres, value = frame, location = ph_location_type(type = "body"))
新增圖和影象
繪圖和影象也可以新增到PowerPoint文件中。 在下面的程式碼中,我們將ggplot物件新增到新幻燈片中。
library(ggplot2) pres <- add_slide(pres, layout = "Blank", master = "Office Theme") sample_plot <- ggplot(data = frame) geom_point(mapping = aes(1:10, a), size = 3) theme_minimal() pres <- ph_with(pres, value = sample_plot, location = ph_location_fullsize())
外部影象可以這樣載入:
pres <- add_slide(pres) pres <- ph_with(pres, external_img("sample_image.png", width = 2, height = 3), location = ph_location_type(type = "body"), use_loc_size = FALSE )
請注意,在這種情況下,如何將影象檔案的名稱以及所需的寬度和高度大小包裝在external_img函式中。
調整字型和顏色
字型大小和顏色可以使用fp_text函式進行調整。 在下面的示例中,我們建立了兩個段落–第一個段落為粗體,第二個段落為綠色。
# create bold text object with size 24 font bold <- fp_text(font.size = 24, bold = TRUE) # create green Arial text object with size 24 font green <- fp_text(font.size = 24, color = "green", font.family = "Arial") # create block list of two paragraphs with the above font specifics pars <- block_list(fpar(ftext("This line is bold", bold)), fpar(ftext("This line is green and Arial", green))) # add slide with paragraphs pres % ph_with(pars, location = ph_location_type(type = "body"))
新增超連結
最後,我們可以使用ph_hyperlink函式將超連結新增到簡報中。 在下面,我們建立一個帶有文字“ Click Here”的超連結,該連結指向https://theautomatic.net。
pres <- add_slide(pres) pres <- ph_with(pres, "Click Here", location = ph_location_type(type = "body")) pres <- ph_hyperlink(pres, href = "https://theautomatic.net")