将两个Data.frame对象的值添加到新的Data.frame中

时间:2015-11-14 21:53:00

标签: r database dataframe aggregate

我是否可以在[R]中请求正确的命令在两个data.frame对象中添加值以生成第三个“聚合”data.frame?以下是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

和...

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

我正在做的事情漫长而繁琐:

 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

1 个答案:

答案 0 :(得分:-1)

以下是重塑

的方法
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)