Move a column to first position in a data frame

dataframe, r

Solution

I don't know if it's worth adding this as an answer or if a comment would be fine, but I wrote a function called `moveme` that lets you do what you want to do with the language you describe. You can find the function at this answer: https://stackoverflow.com/a/18540144/1270695

It works on the `names` of your `data.frame` and produces a character vector that you can use to reorder your columns:

mydf <- data.frame(matrix(1:12, ncol = 4))
mydf
moveme(names(mydf), "X4 first")
# [1] "X4" "X1" "X2" "X3"
moveme(names(mydf), "X4 first; X1 last")
# [1] "X4" "X2" "X3" "X1"

mydf[moveme(names(mydf), "X4 first")]
#   X4 X1 X2 X3
# 1 10  1  4  7
# 2 11  2  5  8
# 3 12  3  6  9

If you're shuffling things around like this, I suggest converting your `data.frame` to a `data.table` and using `setcolorder` (with my `moveme` function, if you wish) to make the change by reference.

In your question, you also mentioned "I just want to pick one column and move it to the start". If it's an arbitrary column, and not specifically the last one, you could also look at using `setdiff`.

Imagine you're working with the "mtcars" dataset and want to move the "am" column to the start.

x <- "am"
mtcars[c(x, setdiff(names(mtcars), x))]

Problem

I would like to have the last column of the data frame moved to the start (as first column). How can I do it in R? My data.frame has about a thousand columns to changing the order wont to. I just want to pick one column and "move it to the start".

Original source

Related problems