简体   繁体   English

dcast和knitr的作用域问题

[英]Scoping issue with dcast and knitr

I've created a simple R file called test.R : 我创建了一个简单的R文件,称为test.R

library(knitr)

file <- "test.Rmd"

k <- function(input, output){
  knit(input, output)
}

k(file, "badtest.md")

knit(file, "goodtest.md")

k(file, "badtest2.md")

Accompanying it is a small Rmd file called test.Rmd : 伴随它的是一个小的Rmd文件,称为test.Rmd

```{r define, echo = FALSE, warning=FALSE} 
suppressPackageStartupMessages(library(data.table))
xsum <- function(x){
  sum(x, na.rm = TRUE)
}
```
```{r, echo = FALSE}
mt <- as.data.table(mtcars)
f <- function(d){
  dcast(d,  drat ~ cyl, fun.aggregate = list(xsum), value.var = "carb") 
}

f(mt)[1:5]

```

The goal is to run the xsum function on the data. 目标是对数据运行xsum函数。 In the first case where the knit call is inside a function ( badtest.md ), it fails with Error in eval(expr, envir, enclos): could not find function "xsum" . 在第一种情况下, knit调用位于函数内部( badtest.md ),它将失败,并Error in eval(expr, envir, enclos): could not find function "xsum"

The second case ( goodtest.md ) is outside of a function and it succeeds. 第二种情况( goodtest.md )在函数之外,并且成功。

The third case ( badtest2.md ) is the same as the first, but it also succeeds now that the second case has run. 第三种情况( badtest2.md )与第一种情况相同,但是由于第二种情况已经运行,它也成功了。

Why does this scoping issue occur and how can I resolve it so that I can use xsum or any custom function? 为什么会出现此作用域问题,如何解决它,以便可以使用xsum或任何自定义函数?

The solution is to pass through the function explicitly as I found out from this comment on the data.table issue page: 解决方案是显式地传递该函数,正如我在data.table问题页面上的此注释中所发现的:

f <- function(d, fun.aggregate){
  dcast(d,  drat ~ cyl, fun.aggregate = fun.aggregate, value.var = "carb") 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM