基于字符向量

时间:2015-09-21 14:25:33

标签: r subset knitr

我实际上是在尝试修改this answer以编程方式为每个变量级别生成包含图的块。

然而,在我的特定情况下,我传递了一个字符向量,用于后续的子集,这似乎是代码失败的根源。

# My report (test.Rmd)

```{r}
library(ggplot2)
library(knitr)
data(diamonds)
diamonds$cut <- factor(gsub(" ", "_", diamonds$cut)) # Get rid of spaces
cut.levels <- levels(diamonds$cut)
```

## Generate report for each level of diamond cut
```{r, include=FALSE}
src <- lapply(cut.levels, function(cut) knit_expand(file = "template.Rmd"))
```

`r knit(text = unlist(src))`

模板(template.Rmd):

```{r, results='asis', echo = FALSE}
cat("### {{cut}} cut")
```

```{r {{cut}}-cut, eval = FALSE}
with(subset(diamonds, cut == "{{cut}}"), 
     plot(carat, price, main = paste("{{cut}}", "cut"))
)

```

使用template.Rmd中设置为eval=FALSE的第二个块运行此操作会产生预期的输出 - 每个块的一系列标头带有回显代码。但是,cut.levels调用中subset字符串的替换值已丢失其引号,我预计,当删除eval=FALSE chunk选项时会导致以下错误:

Quitting from lines 6-8 (test.Rmd) 
Quitting from lines 12-12 (test.Rmd) 
Error in eval(expr, envir, enclos) : object 'Fair' not found
Calls: <Anonymous> ... with -> subset -> subset.data.frame -> eval -> eval

现在正在寻找对象Fair,而不是那些cut == "Fair"的记录。

感谢您的协助!

> sessionInfo()
R version 3.2.1 (2015-06-18)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

1 个答案:

答案 0 :(得分:4)

我看到了2个问题。

首先,正如您所指出的那样,{{cut}}在没有引号的情况下展开,因此您需要将标记包装在引号中。其次,你plot()的结束位置是错误的。它应该运行以下编辑:

### {{cut}} cut

```{r {{cut}}-cut}
with(subset(diamonds, cut == "{{cut}}"), 
     plot(carat, price, main = paste("{{cut}}", "cut"))
)
```