1

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:

Community
  • 1
  • 1
Bobby
  • 1,585
  • 3
  • 19
  • 42

1 Answers1

3

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))
Bobby
  • 1,585
  • 3
  • 19
  • 42
Steven Beaupré
  • 21,343
  • 7
  • 57
  • 77
  • The OP wants to pass in variables, not use character strings. – hrbrmstr Oct 20 '16 at 11:16
  • @hrbrmstr Well, this should work fine with `var <- "__ID"; select_(df, as.name(var))` too, no ? – Steven Beaupré Oct 20 '16 at 11:18
  • 1
    @StevenBeaupré Thanks, this is exactly what I needed. I've made a small edit to your answer so it uses a variable to hold the column name, but that was just a trivial change. Thanks for letting me know about `as.name()` – Bobby Oct 20 '16 at 11:43