Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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 )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading