【发布时间】:2022-01-14 06:22:43
【问题描述】:
我有一个 Excel 表格中的考试问题,我需要以 exam 包要求的格式导出它们,在我的情况下,每个问题都有一个 Rnw 文件。我设法使用循环完成了我需要的事情,我想知道循环的替代方案(例如,创建一个函数,然后与*apply 或purrr::map 的某些实现一起使用?)。这是我的代码,在现实生活中,数据框将从 Excel 导入并包含数百行。
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(glue)
#>
#> Attaching package: 'glue'
#> The following object is masked from 'package:dplyr':
#>
#> collapse
questions <- data.frame(
text = c("A question", "Another question"),
a1 = rep("Option1", 2),
a2 = rep("Option2", 2),
a3 = rep("Option3", 2),
a4 = rep("Option4", 2),
correct = c(1,3),
label = c("Question_1", "Question_2")
)
for(i in 1:nrow(questions)){
q <- slice(questions, i)
solutions <- paste(q$correct == 1:4, collapse=", ") |> noquote()
sink(file=paste0(q$label, ".Rnw"))
glue("\\begin{{question}}\n
{q$text}\n
<<echo=FALSE, results=hide, results=tex>>=
questions=c('{q$a1}', '{q$a2}', '{q$a3}', '{q$a4}')
solutions <- c({solutions})
answerlist(questions)
@\n
\\end{{question}}") |> print()
sink()
}
由reprex package 创建于 2021-12-09 (v2.0.1)
【问题讨论】: