Home > Enterprise >  In R dataframe, is there way to change variables(columns) sequence automatically?
In R dataframe, is there way to change variables(columns) sequence automatically?

Time:10-13

In R dataframe, is there way to change variables(columns) sequence automatically?

the 'raw_data' is the dataframe, currently i change the columns sequence using 'dplyr/select' by input a vector "a1,a2,a3,b1,b2,c1,c2". the result as dataframe 'tidy_data'

library(tidyverse)    
raw_data <- data.frame(a3=1:3,
                           b2=1:3,
                           c2=1:3,
                           c1=1:3,
                           a2=1:3,
                           b1=1:3,
                           a1=1:3)
    
    tidy_data <- raw_data %>% select(a1,a2,a3,b1,b2,c1,c2)

CodePudding user response:

Does this work:

raw_data[sort(names(raw_data))]
  a1 a2 a3 b1 b2 c1 c2
1  1  1  1  1  1  1  1
2  2  2  2  2  2  2  2
3  3  3  3  3  3  3  3

CodePudding user response:

Or with the order function:

> raw_data[order(colnames(raw_data))]
  a1 a2 a3 b1 b2 c1 c2
1  1  1  1  1  1  1  1
2  2  2  2  2  2  2  2
3  3  3  3  3  3  3  3
> 

Or with select:

> raw_data %>% select(order(colnames(.)))
  a1 a2 a3 b1 b2 c1 c2
1  1  1  1  1  1  1  1
2  2  2  2  2  2  2  2
3  3  3  3  3  3  3  3
> 
  • Related