[R] Help Needed on Merging Columns by Summation
Gabor Grothendieck
ggrothendieck at gmail.com
Wed Jun 22 16:06:22 CEST 2011
On Wed, Jun 22, 2011 at 2:35 AM, Nabila Binte Zahur <nabila at nus.edu.sg> wrote:
> Dear Sirs/Madam,
>
> I am a beginner to R, and I am currently working on a data matrix which looks like this:
>
>> head(oligo)
>
> ko:K00001 ko:K00003 ko:K00005 ko:K00008 ko:K00009 ko:K00010 ko:K00012
> AAA 370 631 365 67 164 455 491
> KAA 603 1208 170 157 68 495 922
> NAA 60 110 10 7 44 51 94
> DAA 183 802 41 62 26 166 263
> CAA 58 12 58 1 1 23 8
> TAA 451 468 201 90 131 320 518
>
>
> For certain specific columns, I need to merge the columns in such a way that the elements get added together.
>
> For example, in order to merge the first and the second columns, my output for the first row shld be
>
> ko:K00001/ko:K00003
> AAA 1001 (i.e. 370+631)
> KAA 1811 (i.e. 603+1208)
>
>
> and so on for the whole column.
>
Define a by vector (called collapse here) that has equal numbers for
columns to be collapsed and distinct numbers for those that are not to
be collapsed. We then transpose, use rowsum and transpose back.
Assuming DF is the data frame we have:
collapse <- c(1, 1, 3:7)
setNames(as.data.frame(t(rowsum(t(DF), collapse))),
tapply(names(DF), collapse, paste, collapse = "/"))
--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com
More information about the R-help
mailing list