[R] Inserting column in between

David L Carlson dcarlson at tamu.edu
Mon Aug 1 19:35:04 CEST 2011


Not when I do it.

> a <- data.frame(A=1:10, B=11:20, D=31:40, E=41:50)
> a
    A  B  D  E
1   1 11 31 41
2   2 12 32 42
3   3 13 33 43
4   4 14 34 44
5   5 15 35 45
6   6 16 36 46
7   7 17 37 47
8   8 18 38 48
9   9 19 39 49
10 10 20 40 50
> b <- cbind(a[,1:2], C=21:30, a[,3:4])
> b
    A  B  C  D  E
1   1 11 21 31 41
2   2 12 22 32 42
3   3 13 23 33 43
4   4 14 24 34 44
5   5 15 25 35 45
6   6 16 26 36 46
7   7 17 27 37 47
8   8 18 28 38 48
9   9 19 29 39 49
10 10 20 30 40 50

----------------------------------------------
David L Carlson
Associate Professor of Anthropology
Texas A&M University
College Station, TX 77843-4352



-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
Behalf Of Bert Gunter
Sent: Monday, August 01, 2011 12:18 PM
To: Sarah Goslee
Cc: r-help at r-project.org
Subject: Re: [R] Inserting column in between

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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
"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

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list