Home > Enterprise >  Is it possible to put dplyr pipes into a function to consolidate repetitive code in R?
Is it possible to put dplyr pipes into a function to consolidate repetitive code in R?

Time:12-02

I am making a powerpoint in R using officer. All my slides have the same layout so I am trying to write a function to consolidate the code.

suppressPackageStartupMessages({
  library(officer)
  library(tidyverse)
})

This is an example of what I have:

srcfile <- file.path( R.home("doc"), "html", "logo.jpg" )
test_1 <- read_pptx() %>%
  add_slide() %>%
  ph_with(external_img(srcfile, width = 2.78, height = 2.12),
          location = ph_location_type(type = "body"), 
          use_loc_size = FALSE ) %>%
  
  add_slide() %>%
  ph_with(external_img(srcfile, width = 2.78, height = 2.12),
          location = ph_location_type(type = "body"), 
          use_loc_size = FALSE )

print(test_1, target = "test_1.pptx")

I tried consolidating the code below and received this error: Error in new_slide(., image = srcfile) : unused argument (.) .

Attempted solution:

new_slide <- function(image) 
{
  add_slide() %>%
    ph_with(external_img(image, width = 2.78, height = 2.12),
            location = ph_location_type(type = "body"), 
            use_loc_size = FALSE )
}

test_2 <- read_pptx() %>%
  new_slide(image = srcfile) %>%
  new_slide(image = srcfile)

print(test_1, target = "test_2.pptx")

CodePudding user response:

The %>% operator passes along values via the first parameter to the function. Do in order to continue the chain, you need to capture that first value. For example

new_slide <- function(x, image) {
    x %>%
    add_slide() %>%
    ph_with(external_img(image, width = 2.78, height = 2.12),
            location = ph_location_type(type = "body"), 
            use_loc_size = FALSE )
}
  • Related