自动比较R代码与解决方案脚本

时间:2019-02-07 16:12:40

标签: r automated-tests compare

当对象的名称不同且脚本长于2行时,如何自动将R脚本与解决方案脚本进行比较。

解决方案脚本:

table(bfi_i$age)
barplot(table(bfi_i$age),
        xlab = "Alter",
        ylab = "n")
x <- 3

示例脚本:

table(bfi_i$age) # correct
barplot(table(bfi_i$age)) # bracket too early
        xlab = "Altersgruppe" # missing comma
        ylab = "Haufigkeit" # missing comma
        col = c("lightblue", "mistyrose") # the place for the bracket
y <- 3 # correct

testwhat软件包似乎对更复杂的脚本没有帮助。 我希望将其保留在RStudio中,因为它必须自然而然地使用R。

有人可以帮我吗?

到目前为止,我一直在尝试。相当混乱,还没有解决方案表:

# read all files
setwd('H:/')
folder_name <- getwd()
(all_files <- list.files(folder_name, include.dirs = F, recursive = F,
                        ignore.case = TRUE, pattern = glob2rx("*.R")))
student_files <- sapply(all_files, function(file) {
  student_code <- data.frame(Check = as.character(""),
                             read.delim(file, header = F, sep = "#",
                                        stringsAsFactors = F, quote = "`" 
                                        ))
  names(student_code)[2] <- "commands"
  names(student_code)[3] <- "comments"
  student_code
})

####check single files####
Erg1 <- student_files[[1]][1:3]
Erg1$Check<- as.character(Erg1$Check)
Erg1$commands <- trimws(Erg1$commands, which = c("both"))
test <- Erg1

setwd("H:/")
load("file.rda")

feedback <- c("correct", "1", "2")
x = 0; z = 0; cat('\14'); dev.off()
for(i in 1 : (nrow(test))) {
  cat(crayon::green(paste0(row.names(test[i, ]),". l: ", test[i, 3]), "\n"))
  if (test[i, 2] != "rm(list=ls())" && test[i, 2] != "cat('\\014')" && 
      test[i, 2] != "dev.off()" && !grepl("load", test[i, 2]) && 
      !grepl("setwd", test[i, 2])) {
    if (test[i, 2] != ""){
      # longer commands
      if (stringr::str_sub(test[i, 2], nchar(test[i, 2])) == ",") { 
        x = x + 1; next
      } else {
        cat("\n"); cat(crayon::underline(paste(test[(i - x) : i, 2], "\n")))
        test[(i - x), 1] <- sample(feedback, 1)
        tryCatch(print(z <- eval(parse(text = test[(i - x) : i, 2]))),
                 warning = function(w)  {
                   test[(i - x), 1] <- "Warning" # doesn't work yet
                   cat(crayon::red(crayon::bold("Warn_DF \n")))
                 },
                 error = function(e) {
                   test[(i - x), 1] <- "error" # doesn't work yet
                   cat(crayon::red(crayon::bold("error_DF \n")))
                 }
        )
        if (is.na(z) || is.character(z) || is.null(z)) {
          cat(crayon::red(crayon::bold("check_DF \n")))
        } else {cat(crayon::bold(paste(sample(feedback, 1), "\n")))}
        browser() # stop for each task
        x = 0}}}}

0 个答案:

没有答案