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....@cbs.dk Priv: pda...@gmail.com "Døden skal tape!" --- Nordahl Grieg ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.