2
quote(# this is a comment)

How can I do something like the above?

2 Answers2

3

quote() captures the original code in its wholeSrcref attribute, which preserves comments:

x <- quote({
    ## This is a comment
})

src <- attributes(x)$wholeSrcref          # <--- preserves the comment

However, this returns an object of class srcref, not a true expression that can be passed to eval(). Depending on what you are trying to do, you may find these functions for manipulating srcref objects useful. For example,

as.character(src)[2]
[1] "    ## This is a comment"
Artem Sokolov
  • 13,196
  • 4
  • 43
  • 74
0

It is not quite clear what you are trying to achieve, but the following things should work:

  1. You can easily store hashtags within strings:

    string<- "# this is a comment"

  2. If you need to put this in quotes you can do:

    dQuote("# this is a comment",q = options(useFancyQuotes=FALSE))

This returns: "\"# this is a comment\"" .

The option useFancyQuotes=FALSE is making sure that "normal" quotes (and not typographic quotes) are used. If you leave this parameter out the result would be "“# this is a comment”"

  1. You can also just write quote("# this is a comment") which will return "# this is a comment"
shghm
  • 239
  • 2
  • 8