Bobby Bobby - 1 month ago 13
R Question

Avoiding backtick characters with dplyr

How can I write the argument of

select
without backtick characters? I would like to do this so that I can pass in this argument from a variable as a character string.

df <- dat[["__Table"]] %>% select(`__ID` ) %>% mutate(fk_table = "__Table", val = 1)


Changing the argument of select to
"__ID"
gives this error:

Error: All select() inputs must resolve to integer column positions.
The following do not:
* "__ID"


Unfortunately, the
_
characters in column names cannot be avoided since the data is downloaded from a relational database (FileMaker) via ODBC and needs to be written back to the database while preserving the column names.

Ideally, I would like to be able to do the following:

colName <- "__ID"
df <- dat[["__Table"]] %>% select(colName) %>% mutate(fk_table = "__Table", val = 1)


I've also tried
eval(parse())
:

df <- dat[["__Table"]] %>% select( eval(parse(text="__ID")) ) %>% mutate(fk_table = "__Table", val = 1)


It throws this error:

Error in parse(text = "__ID") : <text>:1:1: unexpected input
1: _
^


By the way, the following does work, but then I'm back to square one (still with backtick symbol).

eval(parse(text="`__ID`")


References about backtick characters in
R
:


Answer

You can use as.name() with select_():

colName <- "__ID"
df <- data.frame(`__ID` = c(1,2,3), `123` = c(4,5,6), check.names = FALSE)
select_(df, as.name(colName))
Comments