问题
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.
回答1:
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]`
来源:https://stackoverflow.com/questions/24472114/use-a-variable-name-with-spaces-inline-in-r-markdown