Select the last n columns of data frame in R

前端 未结 7 1006
礼貌的吻别
礼貌的吻别 2021-01-04 04:42

Is there a way to systematically select the last columns of a data frame? I would like to be able to move the last columns to be the first columns, but maintain the order of

相关标签:
7条回答
  • 2021-01-04 04:46

    Another alternative with dplyr:

    mydata2 <- select(mydata, 2:ncol(data),1)  
    #select any cols from col2 until the last col and place them before col1
    
    0 讨论(0)
  • 2021-01-04 04:47

    I know this topic is a little dead, but wanted to chime in with a simple dplyr solution:

    library(dplyr)
    
    mydata <- mydata %>%
      select(A, B, everything())
    

    Hopefully that helps out any future visitors to this question.

    0 讨论(0)
  • 2021-01-04 04:53

    data frames are just lists, so you can rearrange them as you would any list:

    newdata <- c(mydata[colNamesToStart],
                 mydata[-which(names(mydata) %in% colNamesToStart)])
    
    0 讨论(0)
  • 2021-01-04 04:55

    You can do a similar thing using the SOfun package, available on GitHub.

    library(SOfun)
    
    foo <- moveMe(colnames(mydata2), "A, B before num1")
    
    mydata2[, foo]
    
    #  A B num1 num2
    #1 A B    1   36
    #2 A B    2   37
    #3 A B    3   38
    #4 A B    4   39
    #5 A B    5   40
    

    You can move column names like this example from R Help.

    x <- names(mtcars)
    
    x
    #[1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"
    
    moveMe(x, "hp first; cyl after drat; vs, am, gear before mpg; wt last")
    #[1] "hp"   "vs"   "am"   "gear" "mpg"  "disp" "drat" "cyl"  "qsec" "carb" "wt" 
    
    0 讨论(0)
  • 2021-01-04 05:01

    Using the offset argument in the last_col function, inside select, you can do that.

    Below is an example considering the last two columns, and it in a more generic approach.

    library(dplyr)
    
    mydata <- mydata %>% select(last_col(offset=c(0,1)), everything())
    
    n <- 2
    mydata <- mydata %>% select(last_col(offset=0:(n-1), everything())
    
    0 讨论(0)
  • 2021-01-04 05:03

    You could use something like this:

    move_to_start <- function(x, to_move) {
      x[, c(to_move, setdiff(colnames(x), to_move))]
    } 
    
    move_to_start(mydata2, c('A', 'B'))
    
    #   A B num1 num2
    # 1 A B    1   36
    # 2 A B    2   37
    # 3 A B    3   38
    # 4 A B    4   39
    # 5 A B    5   40
    

    Alternatively, if you want to move the last n columns to the start:

    move_to_start <- function(x, n) {
      x[, c(tail(seq_len(ncol(x)), n), seq_len(ncol(x) - n))]
    } 
    
    move_to_start(mydata2, 2)
    
    #   A B num1 num2
    # 1 A B    1   36
    # 2 A B    2   37
    # 3 A B    3   38
    # 4 A B    4   39
    # 5 A B    5   40
    
    0 讨论(0)
提交回复
热议问题