是否有可能将dplyr管道放入函数中以巩固R中的重复代码?



我正在使用officer在R中制作ppt。我所有的幻灯片都有相同的布局,所以我试着写一个函数来整合代码。

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

这是我所拥有的一个例子:

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

我尝试合并下面的代码并收到这个错误:Error in new_slide(., image = srcfile) : unused argument (.).

试图解决方案:

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

%>%操作符通过第一个参数传递值给函数。为了继续这个链,您需要捕获第一个值。例如

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

最新更新