Use a variable name with spaces inline in R markdown

混江龙づ霸主 提交于 2020-07-15 07:38:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!