rajvijay
rajvijay

Reputation: 1721

arranging columns using dplyr::select without hardcoding

I am loading a csv file. I am trying to arrange the columns based on the of string of column names I have. I have about 50 columns. I am curious as to how do I arrange the columns using

  dplyr::select 

I see the argument it takes are the column names directly, without referring it as a string. So may have to hardcode the name. This is straight forward to do if I refer the dataframe (and avoiding hard code) using

 [

Here is an example

table = data.frame(cnty=c(1,2,3), empcnt1=c(200,300,400), 
wage1=c(40,50,60),empcnt2=c(200,300,400),
wage2=c(40,50,60),empcnt3=c(200,300,400), wage3=c(40,50,60))

col.string <- c("empcnt1","wage1","empcnt2","wage2","empcnt3","wage3","cnty")
table1 <- table[col.string]

Using

dplyr::select
table2 <- select(table,empcnt1,wage1,empdiff,empcnt2,wage2,empcnt3,wage3,cnty)
table2 <- select(table,empcnt1:wage3,cnty)

Note I am not able to leverage the fact I have

col.string

I have about 50 columns, so trying to avoid hard coding when using dplyr:select.

Upvotes: 2

Views: 576

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193687

By the sounds of it, you want to use select_ along with the .dots argument:

> table %>% select_(.dots = col.string)
  empcnt1 wage1 empcnt2 wage2 empcnt3 wage3 cnty
1     200    40     200    40     200    40    1
2     300    50     300    50     300    50    2
3     400    60     400    60     400    60    3

Upvotes: 4

Related Questions