R 考试使用 dplyr 打包奇怪的行为

Flo*_*ald 1 r dplyr r-exams

当我加载 dplyr 库时,我注意到 R 考试包中的奇怪行为。下面的示例仅在我显式调用 dplyr 命名空间时才有效,如注释中所示。请注意,该错误仅发生在新会话中,即您需要重新启动 R 才能查看我所看到的内容。您需要将以下内容放在一个文件中exam.Rmd,然后调用

library(exams)
library(dplyr)
exams2html("exam.Rmd")  # in pwd

# this is exam.Rmd
```{r datagen,echo=FALSE,results='hide',warning=FALSE,message=FALSE}
df = data.frame(i = 1:4, y = 1:4, group = paste0("g",rep(1:2,2)))
# works:
b2 = diff(dplyr::filter(df,group!="g1")$y)
b3 = diff(dplyr::filter(df,group!="g2")$y)
# messes up the complete exercise:
# b2 = diff(filter(df,group!="g1")$y)
# b3 = diff(filter(df,group!="g2")$y)
nq = 2
questions <- solutions <- explanations <- rep(list(""), nq)
type <- rep(list("num"),nq)

questions[[1]] = "What is the value of $b_2$ rounded to 3 digits?"
questions[[2]] = "What is the value of $b_3$ rounded to 3 digits?"
solutions[[1]] = b2
solutions[[2]] = b3
explanations[[1]] = paste("You have you substract the conditional mean of group 2 from the reference group 1. gives:",b2)
explanations[[2]] = paste("You have you substract the conditional mean of group 3 from the reference group 1",b3)
```


Question
========
You are given the following dataset on two variables `y` and `group`. 

```{r showdata,echo=FALSE}
# kable(df,row.names = FALSE,align = "c")
df
```

some text with math

$y_i = b_0 + b_2 g_{2,i}  + b_3 g_{3,i} + e_i$

```{r questionlist, echo = FALSE, results = "asis"}
answerlist(unlist(questions), markup = "markdown")
```

Solution
========

```{r sollist, echo = FALSE, results = "asis"}
answerlist(unlist(explanations), markup = "markdown")
```

Meta-information
================
extype: cloze
exsolution: `r paste(solutions,collapse = "|")`
exclozetype: `r paste(type, collapse = "|")`
exname: Dummy Manual computation
extol: 0.001
Run Code Online (Sandbox Code Playgroud)

Ach*_*eis 5

感谢您提出这个问题并感谢@hrbrmstr 对问题的一部分进行解释。但是,仍然缺少一部分解释:

  • 当然,问题的根源在于两者statsdplyrexportfilter()功能不同。并且它可以取决于首先找到哪个功能的各种因素。
  • 在交互式会话中,以正确的顺序加载包statsdplyr随后自动加载就足够了。因此这有效:
    library("knitr")
    library("dplyr")
    knit("exam.Rmd")
  • 我花了一点时间才弄清楚当你这样做时有什么不同:
    library("exams")
    library("dplyr")
    exams2html("exam.Rmd")
  • 事实证明,在后者的代码块knit()被称为exams2html(),因此NAMESPACE该的exams包,因为它完全导入整个改变搜索路径stats包。因此,stats::filter()被发现之前dplyr::filter(),除非代码在其中的环境评价dplyr装载如.GlobalEnv。(有关更多详细信息,请参阅@hrbrmstr 的答案)

由于exams包导入整个stats包没有紧迫的理由,我将其更改NAMESPACE为仅选择性导入所需的功能(不包括该filter()功能)。请从 R-Forge 安装开发版本:

install.packages("exams", repos = "http://R-Forge.R-project.org")
Run Code Online (Sandbox Code Playgroud)

然后你的 .Rmd 可以被编译,而dplyr::...不仅仅是包含library("dplyr")- 无论是在 .Rmd 中还是在调用 .Rmd 之前exams2html()。两者现在都应该按预期工作。