-1

Can I ask for the right command in [R] to add the values in two data.frame objects to produce a third "aggregate" data.frame? Here's the data from this post:

Mercy Hospital
Type         A    B      C    D      E    All
Operations  359  1836   299   2086  149  4729
Successful  292  1449   179   434   13   2366

and...

Hope Hospital 
Type          A   B  C   D   E   All
Operations   88 514 222 86  45   955
Successful   70 391 113 12  2    588

The way I am doing is long and cumbersome:

 rbind(Hope[1,] + Mercy[1,], Hope[2,] + Mercy[2,])

                 A    B   C    D   E  All
    Operations 447 2350 521 2172 194 5684
    Successful 362 1840 292  446  15 2954
Community
  • 1
  • 1
Antoni Parellada
  • 4,253
  • 6
  • 49
  • 114

1 Answers1

-1

Here is a way to do it with reshaping

library(dplyr)
library(tidyr)

list(hope = Hope, mercy = Mercy) %>%
  bind_rows(.id = "hospital") %>%
  gather(variable, value, -hospital, -Type) %>%
  group_by(Type, variable) %>%
  summarize(value = sum(value)) %>%
  spread(variable, value) 
bramtayl
  • 4,004
  • 2
  • 11
  • 18
  • What if the columns were in a different order? Or what if one had more letters than the other? – bramtayl Nov 15 '15 at 00:10
  • 1
    Just `Mercy + Hope[names(Mercy)]` ? – David Arenburg Nov 15 '15 at 00:12
  • 1
    I see what you're saying. But I think this way is more flexible. It allows as many hospitals as you want, with as many or few common variables in whatever order. – bramtayl Nov 15 '15 at 00:18
  • @DavidArenburg Here's what I was looking for, circumventing the "Type" issue that I hadn't perceived initially:: `data <- cbind(Type=Mercy[,1], Mercy[-1] + Hope[-1])`. And, yes, *now* I am building on your tip in your comment on the OP. – Antoni Parellada Nov 15 '15 at 04:52
  • @AntoniParellada Yes. Obviously you'll need to add that column, I haven't write as is just too obvious. Also, what you mean by "*now*"? So you are saying that there is a substantial difference between `Mercy + Hope` and `Mercy[-1] + Hope[-1]` ? Or between `Mercy[-1] + Hope[-1]` and `cbind(Type=Mercy[,1], Mercy[-1] + Hope[-1])`? It's *exactly* the same thing with some small cosmetics. If we would think your way, we would never close a single questions as a duplicate, because it's never the *exact* thing. The idea is that the comment solves your problem, and without it you wouldn't solve it. – David Arenburg Nov 15 '15 at 06:56
  • @DavidArenburg Please believe me when I say that there was never anything untoward, at least not on purpose. I come to SO as a guest because I don't have background in coding (very far from it), and appreciate the help from people of your caliber. I had been trying with `+` and the `Type` got in the way. Your `Hope[-1]` suggestion was key to getting what I needed. So thank you. – Antoni Parellada Nov 15 '15 at 19:07