[R] Inserting column in between

Bert Gunter gunter.berton at gene.com
Mon Aug 1 20:13:59 CEST 2011


Thanks Sarah and David.

Yes, but note this:

> z <- data.frame(a=1:2,b=3:4)
> z
  a b
1 1 3
2 2 4
> newdat <- 5:6
> cbind(z[,1],newdat,z[,2])
       newdat
[1,] 1      5 3
[2,] 2      6 4

> cbind.data.frame(z[,1],newdat,z[,2])
  z[, 1] newdat  z[, 2]
1      1       5        3
2      2       6        4

Aha moment! -- You need drop=FALSE:

 cbind(z[,1,drop=FALSE],newdat,z[,2,drop=FALSE])
  a newdat b
1 1      5 3
2 2      6 4


So your solution does not work in general (and you may not have
intended it to); while mine does, but is blatantly clumsy. I would say
the "better" approach is merely to add the drop = FALSE option to
yours even though it is unnecessary in your simple example:

 cbind(x[,1:2,drop = FALSE], newcol, x[,3:ncol(x)], drop= FALSE)

... and I would definitely count this as an R 'gotcha' . (and it has
gotcha'ed me before).

Cheers,
-- Bert


On Mon, Aug 1, 2011 at 10:37 AM, Sarah Goslee <sarah.goslee at gmail.com> wrote:
> Bert,
>
> On Mon, Aug 1, 2011 at 1:17 PM, Bert Gunter <gunter.berton at gene.com> wrote:
>> Doesn't work -- you lose column names.
>
> But I don't lose column names:
>
>> x <- data.frame(A=1:3, B=1:3, C=1:3, D=1:3, E=1:3)
>> x
>  A B C D E
> 1 1 1 1 1 1
> 2 2 2 2 2 2
> 3 3 3 3 3 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
>
> It's even possible to change names in the cbind() statement:
>
>> cbind(x[,1:2], Y=newcol, x[,3:ncol(x)])
>  A B Y C D E
> 1 1 1 4 1 1 1
> 2 2 2 5 2 2 2
> 3 3 3 6 3 3 3
>
> If for some reason it isn't working for you, you might try explicitly calling
> cbind.data.frame() instead of the default cbind().
>
>
>> 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])
>
> This shouldn't be necessary, I think. What happens if you use my
> above example?
>
> Sarah
>
>
>> 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