我有一個 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 包(v2.0.1)于 2021 年 12 月 9 日創建
uj5u.com熱心網友回復:
使用map. 您所要做的就是將回圈之間的代碼放入一個函式中:
f = function(i) {
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()
}
然后你可以呼叫它map:
map(1:nrow(questions), f)
或者
1:nrow(questions) %>% map(f)
或與lapply:
lapply(1:nrow(questions), f)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377737.html
