Is there a method for moving a column from one position in a data.frame to the next - without typing an entirely new data.frame()
For example:
a <- b <- c <- d <- e <- f <- g <- 1:100 df <- data.frame(a,b,c,d,e,f,g)
Now let's say I wanted "g" in front of "a"
I could retype it, as
df <- data.frame(g,a,b,c,d,e,f)
But is there not a quicker way? (Imagine 1500+ columns)
Thus, to convert columns of an R data frame into rows we can use transpose function t. For example, if we have a data frame df with five columns and five rows then we can convert the columns of the df into rows by using as. data. frame(t(df)).
To move a column to first in the dataframe, we use relocate() with the column name we want to move. This will move the column of interest to the first column. We can also move the column of interest to a location after another column in the dataframe.
The subset
function has a nice select
argument that gives a convenient way to select ranges of columns by name:
df <- subset(df, select=c(g,a:f))
I wrote this function recently called moveme
. It's designed to work on vectors, with the intent of shuffling column orders around.
Here's the function:
moveme <- function (invec, movecommand) { movecommand <- lapply(strsplit(strsplit(movecommand, ";")[[1]], ",|\\s+"), function(x) x[x != ""]) movelist <- lapply(movecommand, function(x) { Where <- x[which(x %in% c("before", "after", "first", "last")):length(x)] ToMove <- setdiff(x, Where) list(ToMove, Where) }) myVec <- invec for (i in seq_along(movelist)) { temp <- setdiff(myVec, movelist[[i]][[1]]) A <- movelist[[i]][[2]][1] if (A %in% c("before", "after")) { ba <- movelist[[i]][[2]][2] if (A == "before") { after <- match(ba, temp) - 1 } else if (A == "after") { after <- match(ba, temp) } } else if (A == "first") { after <- 0 } else if (A == "last") { after <- length(myVec) } myVec <- append(temp, values = movelist[[i]][[1]], after = after) } myVec }
Usage is simple. Try these out:
moveme(names(df), "g first") moveme(names(df), "g first; a last; e before c")
Of course, using it to reorder the columns in your data.frame
is straightforward:
df[moveme(names(df), "g first")]
And for data.table
s (moves by reference, no copy) :
setcolorder(dt, moveme(names(dt), "g first"))
The basic options are:
Compounded moves are separated by a semicolon.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With