[R] sum column by colnames

Henrique Dallazuanna wwwhsd at gmail.com
Wed Jan 20 14:22:39 CET 2010


Try this:

> m <- merge(data1, data2, by = 0, all = TRUE, sort = FALSE)
> sapply(unique(union(names(data1), names(data2))), function(n)Reduce('+', m[grep(n, names(m))]))

On Wed, Jan 20, 2010 at 10:59 AM, Alfredo Alessandrini
<alfreale74 at gmail.com> wrote:
> Hi,
>
> I've this dataframes:
>
>> data1
>             1        2 3         4             5                6
> 5    0.4963017 0 0 0.2481509  1.9852069 0.4963017
> 10   0.0000000 0 0 0.0000000  0.6317266 0.0000000
> 15   0.0000000 0 0 0.0000000  0.0000000 0.0000000
> 20   0.0000000 0 0 3.3955301  0.0000000 0.0000000
> 25   0.0000000 0 0 0.0000000  0.0000000 0.0000000
> 30   0.0000000 0 0 0.0000000  0.0000000 0.0000000
> 35   0.0000000 0 0 0.0000000  0.0000000 0.0000000
>
>> data2
>           1        4              5                6
> 5    0.00000  0.00000  0.00000  0.0000000
> 10   0.00000  0.00000  0.00000  0.5849502
> 15   0.00000  0.00000  0.00000  0.0000000
> 20   0.00000  0.00000  0.00000  0.0000000
> 25   0.00000 10.49815  0.00000  0.0000000
>
> Can I sum the dataframe, by colnames?
>
> The sum is:
>
>             1        2 3         4             5                6
> 5    0.4963017 0 0 0.2481509  1.9852069 0.4963017
> 10   0.0000000 0 0 0.0000000  0.6317266 0.5849502
> 15   0.0000000 0 0 0.0000000  0.0000000 0.0000000
> 20   0.0000000 0 0 3.3955301  0.0000000 0.0000000
> 25   0.0000000 0 0 10.498150   0.0000000 0.0000000
> 30   0.0000000 0 0 0.0000000  0.0000000 0.0000000
> 35   0.0000000 0 0 0.0000000  0.0000000 0.0000000
>
>
> Thanks,
>
> Alfredo
>
> ______________________________________________
> 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.
>



-- 
Henrique Dallazuanna
Curitiba-Paraná-Brasil
25° 25' 40" S 49° 16' 22" O



More information about the R-help mailing list