Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a variable name with spaces inline in R markdown

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.

like image 663
Ben Avatar asked Jun 29 '14 00:06

Ben


People also ask

Can you have spaces in variable names in R?

R variables cannot have spaces.

How do I add a space in R markdown?

To create vertical space (Markdown to PDF), I use &nbsp; This command works like \vspace{12pt} for latex.

How do I add an inline code in R markdown?

Code results can be inserted directly into the text of a . Rmd file by enclosing the code with `r ` . The file below uses `r ` twice to call colorFunc , which returns “heat.

How do you show spaces in R?

RStudio can reveal information about the whitespace in a file: RStudio > Preferences… > Code > Display > “Show whitespace characters”.


1 Answers

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]`
like image 96
baptiste Avatar answered Oct 11 '22 17:10

baptiste