[R] pasting columns of a dataframe together

Bert Gunter gunter.berton at gene.com
Thu Jun 27 00:45:13 CEST 2013


Anika:

1. You do realize that all columns of your result will be character
(even if they started out as numeric).

2. That being the case, all your data frame columns can be considered
to be character to begin with.

3. That being the case, convert your data frame to a matrix: mdf <-
as.matrix(df)

4. Then since, paste() is vectorized and recycles:

d <- dim(mdf)
mdf<- paste(mdf[,1],mdf)
dim(mdf) <- d

Cheers,
Bert

On Wed, Jun 26, 2013 at 3:21 PM, Anika Masters <anika.masters at gmail.com> wrote:
> Given the size of my dataframe (>400 columns, >35000 rows), I should
> have clarified that speed and efficiency is perhaps as important as
> "elegance", and I'd like to use the examples to learn about any
> corrections and improvements I can make in the examples I provided.
> Thanks for any help you can offer. (I am using R x64 2.15.2 on Windows
> 7.)
>
> On Wed, Jun 26, 2013 at 3:14 PM, Anika Masters <anika.masters at gmail.com> wrote:
>> I want  to "paste" the contents of the first column of a dataframe
>> with all the columns of the same dataframe.
>>
>>
>>
>> What is a "good" way to do this, perhaps something more elegant than
>> what I have below.  (My actual dataframe has ~400 columns and ~35000
>> rows.)
>>
>>
>>
>> example1:
>>
>> mydf <- data.frame( matrix(data=1:15, nrow=5, ncol=3) )
>>
>> mydf2 <- mydf
>>
>> temp2 <- paste(unlist(mydf[,1]) , unlist(mydf), sep="_")
>>
>> mydf2[ ,] <- temp2
>>
>>
>>
>> example2:
>>
>> mydf2 <- mydf
>>
>>
>>
>> for(i in 1:ncol(mydf2) ) {
>>
>> mydf2[i] <- paste( mydf[,1], mydf[ ,i], sep='_')
>>
>> }
>
> ______________________________________________
> 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.



-- 

Bert Gunter
Genentech Nonclinical Biostatistics

Internal Contact Info:
Phone: 467-7374
Website:
http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-biostatistics/pdb-ncb-home.htm



More information about the R-help mailing list