How to add new column to an dataframe (to the front not end)?

后端 未结 6 1591
情深已故
情深已故 2020-11-30 23:55

How to add a new variable to an existing data frame, but I want to add to the front not end. eg. my dataframe is

b c d
1 2 3
1 2 3
1 2 3

I

6条回答
  •  心在旅途
    2020-12-01 00:26

    Add column "a"

    > df["a"] <- 0
    > df
      b c d a
    1 1 2 3 0
    2 1 2 3 0
    3 1 2 3 0
    

    Sort by column using colum name

    > df <- df[c('a', 'b', 'c', 'd')]
    > df
      a b c d
    1 0 1 2 3
    2 0 1 2 3
    3 0 1 2 3
    

    Or sort by column using index

    > df <- df[colnames(df)[c(4,1:3)]]
    > df
      a b c d
    1 0 1 2 3
    2 0 1 2 3
    3 0 1 2 3
    

提交回复
热议问题