0

I've a data frame with some variable, say

v1 v2 v3 v4 v5 v6

and I have a numeric vector

ord <- c(0, 3, 4, 1, 5, 2)

I want to sort the columns of the data frame by the vector

var:  v1 v2 v3 v4 v5 v6
order: 0  3  4  1  5  2

Result expected:

v1 v4 v6 v2 v3 v5

Any ideas? Thank you very much

Gianmarco M
  • 71
  • 1
  • 6
  • 1
    How is `v1 v2 v3 v4 v5 v6` a data.frame? Is it a data.frame with one column and 6 rows? Or are those separate columns? It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Feb 01 '19 at 21:46
  • Thanks for the suggestion! – Gianmarco M Feb 04 '19 at 17:47

1 Answers1

0

Simple example.

df <- data.frame(v1=1,v2=1,v3=1,v4=1,v5=1,v6=1)
df
#   v1 v2 v3 v4 v5 v6
# 1  1  1  1  1  1  1

It helps if you provide data in an unambiguous state that we can use and copy. In future questions, if you can provide something like this code for df, it'll help a lot. Another method when the frame is already made from something else is to use dput(df) and post the output. (Please be careful to not flood the screen with way-too-much data, you might need dput(head(df)) instead or something other method for cutting the volume of data while keeping it representative for your question.)

structure(list(v1 = 1, v2 = 1, v3 = 1, v4 = 1, v5 = 1, v6 = 1), class = "data.frame", row.names = c(NA, 
-1L))

The answer to your question

ord  <- c(0, 3, 4, 1, 5, 2)
df[ order(ord) ]
#   v1 v4 v6 v2 v3 v5
# 1  1  1  1  1  1  1

Some frame-like tools (e.g., data.table) really prefer the proper column second-argument indexing, so this works just as well:

df[ ,order(ord) ]
#   v1 v4 v6 v2 v3 v5
# 1  1  1  1  1  1  1

library(data.table)
as.data.table(df)[ , order(ord), with=FALSE ]
#    v1 v4 v6 v2 v3 v5
# 1:  1  1  1  1  1  1

library(dplyr)
as.tbl(df)[ , order(ord) ]
# # A tibble: 1 x 6
#      v1    v4    v6    v2    v3    v5
#   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1     1     1     1     1     1     1
r2evans
  • 141,215
  • 6
  • 77
  • 149