'sum all rows pairwise in two data frames and save to matrix

I have a data frame df1 and a data frame df 2

df1

colA colB ...
30    2   ...
3     100 ...
15    9   ...
..    ..  ...

df2

colA colB ...
10    200 ...
0     10  ...
55    1   ...
..    ..  ...

I would like to sum all the rows in colA of df1 with colA in df2 and so on for the rest of the columns

Output:

df3

colA colB
40    202
3     110
70    10

I would like to fill up the values to a matrix I have written something like this:

results <- matrix(NA, ncol=ncol(df1), nrow=nrow(df1))
rownames(results) <- rownames(df1)
colnames(results) <- colnames(df1)

for (i in seq(df1)) {
  tempCol1 <- df1[, i]
  for (row in rownames(results))
    for (j in seq(results)){
      results[row,j]<-sum(df1[row, tempCol1 ], 
                          df2[row, tempCol1 ])
}}

it give this error:

Error in [<-(*tmp*, row, j, value = sum(a[row, tempCol1], b[row, tempCol1])) : subscript out of bounds



Solution 1:[1]

You do not have to use a for loop for this problem. Simply add them up:

m = as.matrix(df1 + df2)

Solution 2:[2]

We can do a regular + which will preserve the matrix format and does the elementwise summation, below snippet will get the job done

df1 <- data.frame (
  col1 = c(30, 3, 15),
  col2 = c(2, 100, 19)
)

df2 <- data.frame (
  col1 = c(30, 3, 15),
  col2 = c(2, 100, 19)
)

my_mat1 <- as.matrix(df1)
my_mat2 <- as.matrix(df2)

result = my_mat1 + my_mat2;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bird
Solution 2 Syed M Sohaib