Phil Donovan
Phil Donovan

Reputation: 1265

Translate character commands to SQL with translate_sql()

I have the following character "column == 5" which I want to translate into sql: column = 5. How do I do this?

I have tried unsuccessfully numerous ways such as below:

translate_sql(eval(parse(text="column + 5")))

but translate_sql is a 'literal' environment and this returns <SQL> EVAL(PARSE('column + 5' AS "text")).

I know there has got to be some trick to it!

Upvotes: 1

Views: 173

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545488

What you call “‘literal’ environment” is generally known as a function with non-standard evaluation (NSE). In general there are different ways to work around them, but ‹dplyr› makes this easy by providing standard-evaluation companions to all NSE functions.

The standard-evaluation form of translate_sql is called translate_sql_:

translate_sql_("column + 5")

Furthermore, it’s often easier to go the direct way, rather than parsing a string input:

translate_sql_(quote(column + 5))

In your case there’s no great difference, but in many cases the form at the bottom is more useful since it’s an R object which can be manipulated using R methods. Manipulating a string input so that it still remains syntactically correct is much harder (and, unsurprisingly, less efficient).

Upvotes: 1

Related Questions