how to interpret the example of package glue for the item "backslashes do need to be doubled"

230 views Asked by At

how to interpret the code below , how R treat and evaluate it and get the result "foo",it is hard to understand for me

  `foo}\`` <- "foo"
glue("{
      {
        '}\\'' # { and } in comments, single quotes
        \"}\\\"\" # or double quotes are ignored
        `foo}\\`` # as are { in backticks
      }
  }")
#> foo
1

There are 1 answers

0
Waldi On

You're not the only one to find this example difficult to read.
First, a variable with a funny name is created, and assigned the value "foo":

`foo}\`` <- "foo"
`foo}\``
[1] "foo"

Then glue should evaluate an R expression contained in the first level of curly braces, and itself contained in curly braces:

{
 '}\\'' 
 \"}\\\"\" # or double quotes are ignored
 `foo}\\`` # as are { in backticks
}

As it's a string, backslashes are used to be able to write special characters.

When R parses each line of the expression, it converts the special characters to their value, and removes the comments after #.

The first line of the expression becomes

parse(text = "'}\\''")
expression('}\'')
> eval(expression('}\''))
[1] "}'"

The second line of the expression becomes:

> parse(text='\"}\\\"\"')
expression("}\"")
> eval(expression("}\""))
[1] "}\""

And finally the last line:

> parse(text = "`foo}\\``")
expression(`foo}\``)
> eval(expression(`foo}\``))
[1] "foo"

To sum up, we have :

{
"}'"
"}\""
"foo"
}

[1] "foo"