0

Is there a way to reference columns of a data frame by name within a text block of a Rmarkdown document if the column name includes non-standard characters (for example a space)?

If my one of my column names has a space like the example below, within a code block I can refer to the column by name by surrounding the name with backticks. But if I wanted to include the minimum of this column within the text block since you use backticks to indicate that you are using a code call, so the backticks act as escapes. So `min(my.df$`temp C`)` throws an error because it escapes the code execution.

my.df <- data.frame(id = 1:5, 
                    label = LETTERS[1:5],
                    `temp C` = rnorm(5, mean = 15))
colnames(my.df)[3] <- "temp C"
my.df$`temp C`
# [1] 15.78235 15.51955 14.58482 14.34349 14.38736

min(my.df$`temp C`)
# [1] 14.34349

I could use min(my.df[,3]), but since the data is from an external source, it would silently return the wrong result if the order of the columns in the source file changes. I tried escaping the backtick character in the text block using "\", but it didn't work. Is there an alternate escape character, or some other way to reference a column by name within the text block?

The other approach I thought of using was to create a variable within the a code block before I look to reference it in-line, but this seems a little clunky.

Brian Fisher
  • 1,305
  • 7
  • 17

0 Answers0