8

How can I include inline R code that refers to a variable name that contains spaces or other unusual characters (actual use-case is Pr(>F))? Backticks are the solution in plain R script, but they don't seem to work when the code is inline in a markdown doc. Here's an example:

```{r}
df <- data.frame(mydata= 1:10, yourdata = 20:29)
names(df) <- c("your data", "my data")

```

The first five values of your data are `r df$`your data`[1:5]`

Which when knitted gives:

Quitting from lines 7-9 (test-main.Rmd) 
Error in base::parse(text = code, srcfile = NULL) : 
  2:0: unexpected end of input
1: df$
   ^
Calls: <Anonymous> ... <Anonymous> -> withVisible -> eval -> parse_only -> <Anonymous>
Execution halted

Note that this is different from showing the backticks. All I want to do is have the code executed when the the doc is knitted. My workaround is to assign the value of the odd-named variable to another object with a simple name in the chunk preceding the inline code. But I'm curious about how to directly call inline these objects with unusual names.

Community
  • 1
  • 1
Ben
  • 41,615
  • 18
  • 132
  • 227

1 Answers1

15

In this instance can use normal quotes,

 The first five values of your data are `r df$"your data"[1:5]`

or rather

 The first five values of your data are `r df[["your data"]][1:5]`
baptiste
  • 75,767
  • 19
  • 198
  • 294
  • Thanks! As easy as that, I'm embarrassed I didn't try it in my frenzy of other methods! – Ben Jun 29 '14 at 00:36
  • presumably there are other instances (ggplot?) where this would fail; I don't think knitr's pattern matching can handle nested backticks as well as vanilla markdown, unfortunately. – baptiste Jun 29 '14 at 00:38
  • @baptiste You are right. knitr cannot handle nested backticks. It will stop right after the second backtick. – Yihui Xie Jul 06 '14 at 22:32