Add (insert) a column between two columns in a data.frame

前端 未结 17 1594
耶瑟儿~
耶瑟儿~ 2020-11-28 02:41

I have a data frame that has columns a, b, and c. I\'d like to add a new column d between b and c.

I know I could just add d at the end by using cbind but h

17条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 03:12

    Create an example data.frame and add a column to it.

    df = data.frame(a = seq(1, 3), b = seq(4,6), c = seq(7,9))
    df['d'] <- seq(10,12)
    df
    
      a b c  d
    1 1 4 7 10
    2 2 5 8 11
    3 3 6 9 12
    

    Rearrange by column index

    df[, colnames(df)[c(1:2,4,3)]]
    

    or by column name

    df[, c('a', 'b', 'd', 'c')]
    

    The result is

      a b  d c
    1 1 4 10 7
    2 2 5 11 8
    3 3 6 12 9
    

提交回复
热议问题