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

前端 未结 17 1618
耶瑟儿~
耶瑟儿~ 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:20

    I would suggest you to use the function add_column() from the tibble package.

    library(tibble)
    dataset <- data.frame(a = 1:5, b = 2:6, c=3:7)
    add_column(dataset, d = 4:8, .after = 2)
    

    Note that you can use column names instead of column index :

    add_column(dataset, d = 4:8, .after = "b")
    

    Or use argument .before instead of .after if more convenient.

    add_column(dataset, d = 4:8, .before = "c")
    

提交回复
热议问题