Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)
edited by

I'd like to reorder columns in my data.table x, given a character vector of column names, "neworder":

library(data.table)

x <- data.table(a = 1:3, b = 3:1, c = runif(3))

neworder <- c("c", "b", "a")

Obviously, I could do:

x[ , neworder, with = FALSE]

# or

x[ , ..neworder]

#            c b a

# 1: 0.8476623 3 1

# 2: 0.4787768 2 2

# 3: 0.3570803 1 3

but that would require copying the entire dataset again. Is there another way to do this?

1 Answer

0 votes
by
edited by

You can use the setcolorder() function from the data.table package.

According to R Documentation:

setcolorder 

reorders the columns of data.table, by reference, to the new order provided

The basic syntax of setcolorder is as follows: 

setcolorder(x, neworder=key(x))

Arguments

x

A data.table.

neworder

A character vector of the new column name ordering. May also be column numbers. If length(neworder) < length(x), the specified columns are moved in order to the "front" of x. By default, setcolorder without a specified neworder moves the key columns to the "front" of x.

In your case:

library(data.table)

> x <- data.table(a = 1:3, b = 3:1, c = runif(3))

> x

   a b         c

1: 1 3 0.0456276

2: 2 2 0.4333822

3: 3 1 0.1896660

> setcolorder(x, c("c", "b", "a"))

> x

           c b a

1: 0.0456276 3 1

2: 0.4333822 2 2

3: 0.1896660 1 3

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...