[R] Inserting column in between -- "better" way?

peter dalgaard pdalgd at gmail.com
Tue Aug 2 18:52:18 CEST 2011


On Aug 1, 2011, at 20:50 , David L Carlson wrote:

> Actually Sara's method fails if the insertion is after the first or before
> the last column:
> 
>> x <- data.frame(A=1:3, B=1:3, C=1:3, D=1:3, E=1:3)
>> newcol <- 4:6
>> cbind(x[,1], newcol, x[,2:ncol(x)])
> 

Sarah (sic) is on the right track, just lose the commas so that you don't drop to a vector:

> x <- data.frame(A=1:3, B=1:3, C=1:3, D=1:3, E=1:3)
> newcol <- 4:6
> cbind(x[1], newcol, x[2:ncol(x)])
  A newcol B C D E
1 1      4 1 1 1 1
2 2      5 2 2 2 2
3 3      6 3 3 3 3

Also notice that there is a named form of cbind

> cbind(x[1], foo=4:6, x[2:ncol(x)])
  A foo B C D E
1 1   4 1 1 1 1
2 2   5 2 2 2 2
3 3   6 3 3 3 3


and that things will work (mostly) with matrices and data frames too:

> newcol <- data.frame(x=4:6,y=6:4)
> cbind(x[1], newcol, x[2:ncol(x)])
  A x y B C D E
1 1 4 6 1 1 1 1
2 2 5 5 2 2 2 2
3 3 6 4 3 3 3 3
> cbind(x[1], as.matrix(newcol), x[2:ncol(x)])
  A x y B C D E
1 1 4 6 1 1 1 1
2 2 5 5 2 2 2 2
3 3 6 4 3 3 3 3

(The "mostly" bit refers to some slight oddness occurring if you cbind a matrix with no column names:

> cbind(x[1], cbind(4:6,7:9), x[2:ncol(x)])
  A 1 2 B C D E
1 1 4 7 1 1 1 1
2 2 5 8 2 2 2 2
3 3 6 9 3 3 3 3

)
-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com
"Døden skal tape!" --- Nordahl Grieg



More information about the R-help mailing list