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?
Wrapping the names in backticks does the job.
columns <- c('`CH4+Sulfate-1`', '`CH4+Sulfate-2`', '`CH4+Sulfate-3`')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With