kittygirl
kittygirl

Reputation: 2443

Can knitr `code` option find local object?

In knitr manual

code: (NULL; character) if provided, it will override the code in the current chunk

```{r import_x,code=knitr::include_graphics('x.png')}
png(file='x.png',width=1000,height=1000)
iris %>%
  lapply(., function(x) sum(is.na(x))/length(x)) %>%
  data.frame(.) %>%
  na.omit(.) %>%
  gather(.,factor_key = TRUE) %>%
  ggplot(.,aes(x=key, y=value))+
  geom_bar(stat='identity')+
  theme(axis.text.x = element_text(size=8,angle = 90, vjust = 0.5,hjust=1))
dev.off()
```

In above knitr chunk,I use {r import_x,code=knitr::include_graphics('x.png')} to import x.png and avoid creating x.png again.
But I got error:Error in eval(expr,envir,enclos):cannot find object 'x.png'

Then, I tested, getwd() output the expect path. knitr::include_graphics('x.png') in R script works well, ![ok](x.png)works well.

Where is the problem?

Upvotes: 1

Views: 31

Answers (1)

kittygirl
kittygirl

Reputation: 2443

As @CL 's comment,code option accept character. code="knitr::include_graphics('x.png')" works well.

Upvotes: 1

Related Questions