Home > Software engineering >  sum all rows pairwise in two data frames and save to matrix
sum all rows pairwise in two data frames and save to matrix

Time:02-24

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

CodePudding user response:

Make it to a matrix and add up them.

Directly add two data.frame also works as well.

df1 = data.frame(colA = c(30, 3, 15), colB = c(2, 100, 9))
df2 = data.frame(colA = c(10, 0, 55), colB = c(200, 10, 1))
as.matrix(df1)  as.matrix(df2)
df1 df2

> as.matrix(df1)  as.matrix(df2)
     colA colB
[1,]   40  202
[2,]    3  110
[3,]   70   10

> df1 df2
  colA colB
1   40  202
2    3  110
3   70   10

CodePudding user response:

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

m = as.matrix(df1   df2)

CodePudding user response:

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;
  • Related