首页 > 解决方案 > Move a column based in his colname after a column based in his colname in R

问题描述

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.

标签: r

解决方案


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'))

推荐阅读