[R] Inserting column in between -- "better" way?
peter dalgaard
pdalgd at gmail.com
Tue Aug 2 19:47:00 CEST 2011
On Aug 2, 2011, at 19:17 , Bert Gunter wrote:
> 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?
Well, to be precise they are obtained by indexing a data frame _as_ a list. The result of that is a data frame (always, which was the point).
So you're cbind()-ing data frames, which is what you wanted to do all along.
>
> 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
--
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