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