[英]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
.我正在使用
officer
在 R 制作 powerpoint。 All my slides have the same layout so I am trying to write a function to consolidate the code.我所有的幻灯片都具有相同的布局,因此我正在尝试编写一个 function 来合并代码。
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 (.)
.我尝试整合下面的代码并收到此错误:
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")
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. %>%
运算符通过第一个参数将值传递给 function。为了继续链,您需要捕获第一个值。 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 )
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.