Home > Mobile >  arranging columns based on numeric values in r
arranging columns based on numeric values in r

Time:11-08

I need to arrange column names based on numbering.

Here is a short version of my dataset.

df <- data.frame(id = c(1,2,3),
                 raw_score = c(10,20,30),
                 a = c(1,1,1),
                 b = c(2,3,4),
                 c = c(4,6,7))

names(df) <- c("id","raw_score","2.2","2.3","2.1")

> df
  id raw_score 2.2 2.3 2.1
1  1        10   1   2   4
2  2        20   1   3   6
3  3        30   1   4   7

How can I arrange the columns below?

> df
  id raw_score 2.1 2.2 2.3
1  1        10   4   1   2
2  2        20   6   1   3
3  3        30   7   1   4

CodePudding user response:

Maybe df %>% dplyr::select(id, raw_score,stringr::str_sort(colnames(df[, 3:ncol(df)]), numeric = TRUE)) -> df

  • Related