geoffest
geoffest

Reputation: 39

In R, how can I reorder variables of a tbl within a piped expression?

I have loaded a .csv file, converted to a tbl, renamed variables, mutated, etc. using the following piped expression:

h2020orgs <- read.csv2(file="C:/Users/Geoff/Desktop/Personal/DataCamp/R/R projects/Horizon_2020_orgs_data/cordis_h2020_orgs.csv") %>%
  tbl_df() %>%
  select(1:15) %>%
  rename(projectRcn = ï..projectRcn,
         orgType = activityType,
         orgRole = role,
         orgID = id,
         orgName = name,
         orgShortName = shortName) %>%
  mutate(orgTypeFull = recode(orgType,
                              HES = "Higher education",
                              OTH = "Other",
                              PRC = "Private company",
                              PUB = "Public body",
                              REC = "Research centre"))

Using names(h2020orgs) you can see the index of variables:

names(h2020orgs)
 [1] "projectRcn"         "projectID"          "projectAcronym"     "orgRole"           
 [5] "orgID"              "orgName"            "orgShortName"       "orgType"           
 [9] "endOfParticipation" "ecContribution"     "country"            "street"            
[13] "city"               "postCode"           "organizationUrl"    "orgTypeFull"

I would like to move "orgTypeFull" so it is adjacent (immediately after) to "orgType". I know I can do this using the following standalone call : h2020orgs <- h2020orgs[, c(...)] but is there a way to include this within the piped expression above?

Upvotes: 1

Views: 240

Answers (3)

h3rm4n
h3rm4n

Reputation: 4187

You could use setcolorder from the data.table package:

h2020orgs %>% setcolorder(c(1:8,16:9))

Or without pipes:

setcolorder(h2020orgs, c(1:8,16:9))

Upvotes: 0

Simon Larsen
Simon Larsen

Reputation: 742

You can reorder columns using select() from dplyr, either by name or index.

Using index:

... %>% select(1:8, 16, 9:15)

Upvotes: 0

Daniel Rodak
Daniel Rodak

Reputation: 158

Use select([...], orgType, orgTypeFull, [...]) where [...] means "put other column names there".

Upvotes: 1

Related Questions