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

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

    df <- data.frame(a=c(1,2), b=c(3,4), c=c(5,6))
    df %>%
      mutate(d= a/2) %>%
      select(a, b, d, c)
    

    results

      a b   d c
    1 1 3 0.5 5
    2 2 4 1.0 6
    

    I suggest to use dplyr::select after dplyr::mutate. It has many helpers to select/de-select subset of columns.

    In the context of this question the order by which you select will be reflected in the output data.frame.

提交回复
热议问题