简体   繁体   中英

For Loop to Reorder Columns in R

I am trying to re-order columns in R using a for loop since the column range needs to be dynamic. Does anyone know what is missing from my code?

    Group <- c("A","B","C","D")
    Attrib1 <- c("x","y","x","z")
    Attrib2 <- c("q","w","u","i")
    Day1A <- c(5,4,6,3)
    Day2A <- c(6,5,7,4)
    Day3A <- c(9,8,10,7)
    Day1B <- c(4,3,5,2)
    Day2B <- c(3,2,4,1)
    Day3B <- c(2,1,3,0)

    df <- data.frame(Group, Attrib1,Attrib2,Day1A,Day2A,Day3A,Day1B,Day2B,Day3B)

    day_count <- 3

    for(i in 4:ncol(df)) {
      if (i == day_count+3) break
      df[c(i,day_count+i)]
     }

Here is my desired result:

    df <- data.frame(Group, Attrib1,Attrib2,Day1A,Day1B,Day2A,Day2B,Day3A,Day3B)

So, in theory you can just do sort(colnames(df)[4:ncol(df)]) to get that, but it gets tricky when you have say Day1A..Day10A..Day20A

Below is a quick workaround, to get the numbers and alphabets:

COLS = colnames(df)[4:ncol(df)]
day_no = as.numeric(gsub("[^0-9]","",COLS))
day_letter = gsub("Day[0-9]*","",COLS)
o = order(day_no,day_letter)

To get your final dataframe:

df[,c(colnames(df)[1:3],COLS[o])]

An option with select

library(dplyr)
library(stringr)
df %>% 
   select(Group, starts_with('Attrib'), 
      names(.)[-(1:3)][order(str_remove_all(names(.)[-(1:3)], '\\D+'))])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM