[R] :How to insert a column in a data frame
Rolf Turner
r.turner at auckland.ac.nz
Wed Feb 18 01:19:20 CET 2009
On 18/02/2009, at 12:51 PM, Laura Rodriguez Murillo wrote:
> Hi dear list,
>
> I wonder if somebody can help me with this. I have a text file with
> 300 rows and around 300000 columns and I need to insert a column that
> has the number 1 in every row. This new column should be placed
> between columns 6 and 7.
>
> As an example: I would want to insert a column (consiting just of the
> number 1 in every row, as in column 6) between columns 6 and 7.
>
> 847 847 0 0 2 1 G G T C A G T T C G A C C C G C A A A G G G G A C A
> T T
> 847 847 0 0 2 1 G G T C A G T T C G A C C C G C A A A G G G G A C A
> T T
> 847 847 0 0 2 1 G G T C A G T T C G A C C C G C A A A G G G G A C A
> T T
> 847 847 0 0 2 1 G G T C A G T T C G A C C C G C A A A G G G G A C A
> T T
> 847 847 0 0 2 1 G G T C A G T T C G A C C C G C A A A G G G G A C A
> T T
> 847 847 0 0 2 1 G G T C A G T T C G A C C C G C A A A G G G G A C A
> T T
>
> So the new table would look like this:
>
> 847 847 0 0 2 1 1 G G T C A G T T C G A C C C G C A A A G G G G A C
> A T T
> 847 847 0 0 2 1 1 G G T C A G T T C G A C C C G C A A A G G G G A C
> A T T
> 847 847 0 0 2 1 1 G G T C A G T T C G A C C C G C A A A G G G G A C
> A T T
> 847 847 0 0 2 1 1 G G T C A G T T C G A C C C G C A A A G G G G A C
> A T T
> 847 847 0 0 2 1 1 G G T C A G T T C G A C C C G C A A A G G G G A C
> A T T
> 847 847 0 0 2 1 1 G G T C A G T T C G A C C C G C A A A G G G G A C
> A T T
>
> You can also look at this problem as duplicating column 6.
(1) y <- cbind(x[,1:6],clyde=rep(1,300),x[,7:ncol(x)])
(2) y <- as.data.frame(c(x[1:6],list(clyde=rep(1,300)),x[7:length(x)]))
where x is your original data stored as a matrix or data frame in
method (1),
and as a data frame in method (2), and y is the new data set with the
extra
column of 1's.
Or, if you really are just duplicating column 6:
y <- x[,c(1:6,6,7:ncol(x))]
names(y)[7] <- "clyde" # For consistency with other methods.
These work with your toy example. I haven't tried them out with data
sets of
the size of your real data set.
cheers,
Rolf Turner
######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}
More information about the R-help
mailing list