[R] Inserting column in between
Sarah Goslee
sarah.goslee at gmail.com
Mon Aug 1 19:37:12 CEST 2011
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