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

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

    You can reorder the columns with [, or present the columns in the order that you want.

    d <- data.frame(a=1:4, b=5:8, c=9:12)
    target <- which(names(d) == 'b')[1]
    cbind(d[,1:target,drop=F], data.frame(d=12:15), d[,(target+1):length(d),drop=F])
    
      a b  d  c
    1 1 5 12  9
    2 2 6 13 10
    3 3 7 14 11
    4 4 8 15 12
    

提交回复
热议问题