R对对象重复功能
R Repeat function on object
我正在尝试使用 officer
将图像添加到 Word 文档。我有一个完整目录的图像,我想循环浏览。我遇到的问题是我需要将图像添加到文档中,然后将下一张图像添加到我刚刚通过添加最后一张图像创建的新创建的文档中。
下面是没有循环或函数的代码示例:
library(magrittr)
library(officer)
read_docx() %>% # create document
body_add_img("img1.png", width = 3, height = 4) %>% # add image
body_add_img("img2.png", width = 3, height = 4) %>% # add image
body_add_img("img3.png", width = 3, height = 4) %>% # add image
print(target = "samp.docx") # write document
使用 map
和 lapply
在这种情况下不起作用,因为每次迭代都需要 return 上一次迭代的对象。我尝试用 for
循环编写一个函数,但我想我离题太远了。任何帮助和指点将不胜感激。
我想你可以在这里使用 reduce
。例如使用一点 purrr
library(purrr)
read_docx() %>%
reduce(1:3, function(docx, idx) {
docx %>% body_add_img(paste0("img", idx, ".png"), width = 3, height = 4)
}, .init=.) %>%
print(target = "samp.docx")
reduce 不断将结果反馈给自身。
我不确定您对 for
循环的尝试是什么,但这个简单的循环似乎有效。
library(officer)
data <- read_docx()
image_list <- paste0('img', 1:3, '.png')
for(i in image_list) {
data <- body_add_img(data, i, width = 3, height = 4)
}
print(data, target = "samp.docx")
我正在尝试使用 officer
将图像添加到 Word 文档。我有一个完整目录的图像,我想循环浏览。我遇到的问题是我需要将图像添加到文档中,然后将下一张图像添加到我刚刚通过添加最后一张图像创建的新创建的文档中。
下面是没有循环或函数的代码示例:
library(magrittr)
library(officer)
read_docx() %>% # create document
body_add_img("img1.png", width = 3, height = 4) %>% # add image
body_add_img("img2.png", width = 3, height = 4) %>% # add image
body_add_img("img3.png", width = 3, height = 4) %>% # add image
print(target = "samp.docx") # write document
使用 map
和 lapply
在这种情况下不起作用,因为每次迭代都需要 return 上一次迭代的对象。我尝试用 for
循环编写一个函数,但我想我离题太远了。任何帮助和指点将不胜感激。
我想你可以在这里使用 reduce
。例如使用一点 purrr
library(purrr)
read_docx() %>%
reduce(1:3, function(docx, idx) {
docx %>% body_add_img(paste0("img", idx, ".png"), width = 3, height = 4)
}, .init=.) %>%
print(target = "samp.docx")
reduce 不断将结果反馈给自身。
我不确定您对 for
循环的尝试是什么,但这个简单的循环似乎有效。
library(officer)
data <- read_docx()
image_list <- paste0('img', 1:3, '.png')
for(i in image_list) {
data <- body_add_img(data, i, width = 3, height = 4)
}
print(data, target = "samp.docx")