adamdsmith
adamdsmith

Reputation: 930

knit_expand fails when subsetting based on a character vector

I'm essentially trying to modify this answer to programmatically produce chunks with plots for each level of a variable.

In my particular case, however, I'm passing along a character vector to be used for subsequent subsetting, which seems to be the source of the code failure.

# 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))`

And the template (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"))
)

```

Running this with the second chunk in template.Rmd set to eval=FALSE produces the expected output - a series of headers for each chunk with the echoed code. However, the substituted values from the cut.levels character string in the subset call have lost their quotes which, I expect, causes the following error when the eval=FALSE chunk option is removed:

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

It's now looking for the object Fair rather than those records with cut == "Fair".

Thanks for your assistance!

> 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     

Upvotes: 3

Views: 453

Answers (1)

aaronwolen
aaronwolen

Reputation: 3753

I see 2 problems.

First, as you pointed out, {{cut}} is expanded without quotes so you'll need to wrap the tag in quotes. Second, your closing paren for plot() is misplaced. It should run with the following edits:

### {{cut}} cut

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

Upvotes: 5

Related Questions