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

Sarah Goslee sarah.goslee at gmail.com
Mon Aug 1 19:43:52 CEST 2011


Bert,

On Mon, Aug 1, 2011 at 1:27 PM, Bert Gunter <gunter.berton at gene.com> wrote:
> Folks:
>
> I consider my reply below rather clumsy: One has to keep track of
> index numbers other than that which is inserted and must separately
> change column names. Is there as "essentially better" way to do this,
> either via base R or via an R package. I leave it to you to define
> "essentially better."
>
Having tried your solution with sample data, I'd have to agree. :)
Your approach does mess up the column names, and also doesn't work
if x is a matrix rather than data frame. Mine, using the full cbind(), works
in both cases, preserving the column names and running even if x is
a matrix.

It could be written as a function, but since it's only one line and
really only requires knowing at what position you'd like to add
the new column, it hardly seems worth it unless it's something
to be done repeatedly.

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

Sarah

> Thanks.
>
> Cheers,
> Bert
>
> On Mon, Aug 1, 2011 at 10:17 AM, Bert Gunter <bgunter at gene.com> wrote:
>> Doesn't work -- you lose column names.
>>
>> Try this instead:
>>
>> yourframe[,30:51] <- cbind( newcolumn,yourframe[,30:50])
>>
>> Adjust column names after via:
>>
>> names(yourframe) [30:51] <- c(newcolname,names(yourframe[30:50])
>>
>> Cheers,
>> Bert
>>
>> On Mon, Aug 1, 2011 at 10:10 AM, Sarah Goslee <sarah.goslee at gmail.com> wrote:
>>> x <- cbind(x[,1:29], newcolumn, x[,30:ncol(x)])
>>>
>>> On Mon, Aug 1, 2011 at 12:59 PM, Bansal, Vikas <vikas.bansal at kcl.ac.uk> wrote:
>>>> Dear all,
>>>>
>>>> I have a very simple question.I have data frame of 50 columns and i want to insert a column in 30th position.But i do not want to delete that column.Is it possible to include a column in between, so that new values are in 30th column and 30 th column is now 31st and 31st is 32nd......so on and 50th column is 51st..?I will be very thankful to you.
>>>
-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list