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

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

    Presuming that c always immediately follows b, this code will add a column after b no matter where b is in your data.frame.

    > test <- data.frame(a=1,b=1,c=1)
    > test
      a b c
    1 1 1 1
    
    > bspot <- which(names(test)=="b")
    
    > data.frame(test[1:bspot],d=2,test[(bspot+1):ncol(test)])
      a b d c
    1 1 1 2 1
    

    Or possibly more naturally:

    data.frame(append(test, list(d=2), after=match("b", names(test))))
    

提交回复
热议问题