-2

I would like to be able to move columns to some desired position based solely on the name of the columns, I would like to move a column by name to the desired position after a column with a defined name.

You could use the data iris as an example.

Example:

data(iris)

Actual columns order:

> colnames(iris)
[1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species" 

i would like to put "Petal.Width" after "Sepal.Length" by colnames using code and avoid putting manual inputs like selecting solutions with dplyr.

Thank you very much in advance.

  • Does this answer your question? [How does one reorder columns in a data frame?](https://stackoverflow.com/questions/5620885/how-does-one-reorder-columns-in-a-data-frame) – sertsedat Feb 18 '20 at 13:51
  • 1
    Hi RevanKnight. Welcome to StackOverflow! Please read the info about [how to ask a good question](https://stackoverflow.com/help/how-to-ask) and how to give a [minimale reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610).That way you can help others to help you! – dario Feb 18 '20 at 13:59
  • @sertsedat does not because is a manual approach, i need to automate the task moving a column after another column just by column names. – RevanKnight Feb 18 '20 at 14:14
  • @RevanKnight have you checked all the answers in that question? I'm pretty sure there are some answers that you can use – sertsedat Feb 22 '20 at 08:20

1 Answers1

0

If I understand you correctly, you can achieve what you want using select, by manipulating the vector of column names.

First you need a function that takes a vector of names (assumed to be unique), and two specific entries a and b and move a behind b. I think this function does the trick (even if it is a little clumsy looking).

move <- function(names, a, b) {
  names_without_a <- names[which(names != a)]
  b_pos <- which(names_without_a == b)
  c(names_without_a[1:b_pos], 
    a, 
    names_without_a[(b_pos+1):length(names_without_a)])
}

Now you can use select, like so

df <- 
  iris %>% 
  select(move(colnames(iris), 'Petal.Width', 'Sepal.Length'))