[R] Inserting column in between -- "better" way?
Bert Gunter
gunter.berton at gene.com
Tue Aug 2 19:17:56 CEST 2011
Thanks for this Peter:
>
> 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
>
Am I correct in saying that this is a bit subtle: x[1] and
x[2:ncol(x)] are actually lists with vector components; so you're
cbinding lists, which retain the labels, no?
If so, it's a nice subtlety to remember, anyway.
-- Bert
--
"Men by nature long to get on to the ultimate truths, and will often
be impatient with elementary studies or fight shy of them. If it were
possible to reach the ultimate truths without the elementary studies
usually prefixed to them, these would not be preparatory studies but
superfluous diversions."
-- Maimonides (1135-1204)
Bert Gunter
Genentech Nonclinical Biostatistics
More information about the R-help
mailing list