dataframe - R: Sum column wise value of two/more data frames having same variables (column names) and take Date column as reference -


i want sum 2 data frames having similar columns , take date column reference. eg:

df1:

      date  v1  v2  v3   2017/01/01   2   4   5    2017/02/01   3   5   7  

df2:

      date  v1  v2  v3   2017/01/01   1   3   6   2017/02/01   5   7   7 

i want result as:

df3:

      date  v1  v2  v3   2017/01/01   3   7  11   2017/02/01   8  12  14 

when try add df1 , df2, gives error dates cannot joined. merge not useful here summing values of similar data frames.

you can consider following base r approach.

df3 <- cbind(df1[1], df1[-1] + df2[-1]) df3         date v1 v2 v3 1 2017/01/01  3  7 11 2 2017/02/01  8 12 14 

or dplyr approach.

library(dplyr) df3 <- bind_rows(df1, df2) %>%   group_by(date) %>%   summarise_all(funs(sum)) df3         date    v1    v2    v3        <chr> <int> <int> <int> 1 2017/01/01     3     7    11 2 2017/02/01     8    12    14 

or data.table approach.

library(data.table) df_bind <- rbindlist(list(df1, df2)) df3 <- df_bind[, lapply(.sd, sum), = date] df3          date v1 v2 v3 1: 2017/01/01  3  7 11 2: 2017/02/01  8 12 14 

data:

df1 <- read.table(text = "date    v1    v2    v3   '2017/01/01' 2    4    5    '2017/02/01' 3    5    7",                   header = true, stringsasfactors = false)  df2 <- read.table(text = "date    v1    v2    v3   '2017/01/01'    1    3     6                     '2017/02/01'    5    7     7",                   header = true, stringsasfactors = false) 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -