【问题标题】:Apply function to and output to file individual lines of dataframe将函数应用于文件并输出到数据帧的各个行
【发布时间】:2022-01-14 06:22:43
【问题描述】:

我有一个 Excel 表格中的考试问题,我需要以 exam 包要求的格式导出它们,在我的情况下,每个问题都有一个 Rnw 文件。我设法使用循环完成了我需要的事情,我想知道循环的替代方案(例如,创建一个函数,然后与*applypurrr::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)

【问题讨论】:

    标签: r loops


    【解决方案1】:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多