move a column in r

To move a column in R, we can use the select() function from the dplyr package or the setcolorder() function from the data.table package.

Here's an example using dplyr:

main.r
library(dplyr)

# create sample data frame
df <- data.frame(a = 1:3,
                 b = 4:6,
                 c = 7:9)

# move column "c" to the front
df <- select(df, c, everything())

# view updated data frame
df
217 chars
13 lines

Output:

main.r
  c a b
1 7 1 4
2 8 2 5
3 9 3 6
32 chars
5 lines

Here's an example using data.table:

main.r
library(data.table)

# create sample data table
dt <- data.table(a = 1:3,
                 b = 4:6,
                 c = 7:9)

# move column "c" to the front
setcolorder(dt, c(3, 1:2))

# view updated data table
dt
215 chars
13 lines

Output:

main.r
   c a b
1: 7 1 4
2: 8 2 5
3: 9 3 6
36 chars
5 lines

gistlibby LogSnag