正如一些评论所引用的,如果不知道您的特定操作环境和文件夹结构,这将很难解决,我使用 Windows 10/C 驱动器用户文件夹解决了这个问题,但您可以自定义您的系统。您将需要一个文件夹,其中包含以学校名称(或我创建的 ID)保存的学校所有图像,并且它们都需要采用相同的格式(JPG 或 PNG)。另外,您需要为每个要输出到的区域创建文件夹(openxlsx 可以写入文件但不能为您创建文件夹)。一旦你完成了这些设置,类似的东西应该对你有用,但我强烈建议你参考 openxlsx 文档以获取更多信息:
library(dplyr)
library(openxlsx)
# Load your excel file into a df
# g0 = openxlsx::read.xlsx(<your excel file & sheet..see openxlsx documentation>)
# Replace this tibble with your actual excel file, this was just for an example
g0 = tibble(
Area = c("North","North","North","North"),
School = c("A","A","B","B"),
Student_ID = c(134,221,122,126),
test_score_a = c(24,26,22,25),
test_score_b = c(31,33,21,25))
# Need a numeric school id for the loop
g0$school_id = as.numeric(as.factor(g0$School))
# Loop through schools, filter using dplyr and create a sheet per school
for (i in 1:n_distinct(g0$school_id)){
g1 = g0 %>%
filter(school_id == i)
## Create a new workbook
wb <- createWorkbook(as.character(g1$School))
## Add some worksheets
addWorksheet(wb, as.character(g1$School))
## Insert images
## I left the image as a direct path for example but you can change to a
## relative path once you get it working
img <- system.file("C:","Users","your name","Documents","A","A.jpg", package = "openxlsx")
insertImage(wb, as.character(g1$School), img, startRow = 5, startCol = 3, width = 6, height = 5)
## Save workbook
saveWorkbook(wb, paste0("C://Users//your name//Documents//",g0$Area,"//",g0$school,".xlsx"), overwrite = TRUE)
}