Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass column names in dplyr select without evaluation

Tags:

r

dplyr

I'm trying to programmatically pass column names to a function so that they can be selected in dplyr. The column names will vary so I've tried to use the standard evaluation version of the select function select_. The column names themselves are a bit funny as they contain + and - characters, which I think is causing the issue. Below is a simple example that replicates the error.

library(tibble)
library(dplyr)
data <- data_frame(target_id = 'xyz',
                   `CH4+Sulfate-1` = 1.2, 
                   `CH4+Sulfate-2` = 2, 
                   `CH4+Sulfate-3` = 3)
columns <- c('CH4+Sulfate-1', 'CH4+Sulfate-2', 'CH4+Sulfate-3')
select_(data, .dots = columns)

I get the following error

Error in eval(expr, envir, enclos) : object 'CH4' not found

Which leads me to believe that the names are being evaluated rather than taken as the string. How can I get around this problem without having to rename the columns of the table?

like image 678
cts Avatar asked Aug 24 '16 23:08

cts


1 Answers

Wrapping the names in backticks does the job.

columns <- c('`CH4+Sulfate-1`', '`CH4+Sulfate-2`', '`CH4+Sulfate-3`')
like image 64
Tutuchan Avatar answered Oct 25 '22 07:10

Tutuchan