cephalopod
cephalopod

Reputation: 1906

dplyr::select - programatically rearrange columns using character variable for column name

I want to re-arrange the columns of a df using dplyr::select programatically
A non R user is going to execute the code and this person will provide two inputs as follows:

report.month <- "Jul"
report.year  <- 2017

Only the month will change, all other names in the df will be the same

df that I want to re-arrange looks as follows:

df1 <- data.frame(
     country = "AU",
    Jul_2017 = 500,
    Customer = "some guy")

This is the output that I want

  country Customer Jul_2017
       AU some guy      500

This is what I tried, which does not work and I have run out of ideas:

    reporting.month.name <- as.symbol(paste(report.month, report.year, sep = "_"))

    df1 %>% select(country, Customer, reporting.month.name)
Error: `reporting.month.name` must resolve to integer column positions, not a symbol

Any advice/help is very much appreciated

Upvotes: 0

Views: 5342

Answers (1)

www
www

Reputation: 4224

Remove the as.symbol() from your code, like this:

reporting.month.name <- paste(report.month, report.year, sep = "_")

df1 %>% select(country, Customer, reporting.month.name)

Output:

  country Customer Jul_2017
1      AU some guy      500

Upvotes: 1

Related Questions