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
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))))