# [Solved] Conditional sum of data frames in R

I want to combine data frames and calculate their sum conditionally depending on the value of one of the data frames.

For the example below, if a cell in `df4` is not 0 and not NA, the sum should be `df3 + df4` else the sum should be `df1 + df2 + df3`.

``````> df1
1 2 3
A 0 3 2
B 1 1 0
C 5 0 2

> df2
1 2 3
A 3 2 2
B 4 3 4
C 1 0 3

> df3
1 2 3
A 1 3 4
B 3 4 3
C 1 2 3
``````

The condition depends on this frame:

``````> df4
1  2  3
A  6  0  0
B  0  0 NA
C NA  4  0
``````

With the above examples, this is the expected result:

``````> dfsum
1 2 3
A 7 8 8
B 8 8 7
C 7 6 8
``````

How do I do this in R?

## Solution #1:

``````m1 <- matrix(c(0,1,5,3,1,0,2,0,2),3)
m2 <- matrix(c(3,4,1,2,3,0,2,4,3),3)
m3 <- matrix(c(1,3,1,3,4,2,4,3,3),3)
m4 <- matrix(c(6,0,NA,0,0,4,0,NA,0),3)

msum <- m3 + m4
temp <- m1 + m2 + m3
cond <- is.na(m4) | m4==0

msum[cond] <- temp[cond]

#     [,1] [,2] [,3]
#[1,]    7    8    8
#[2,]    8    8    7
#[3,]    7    6    8
``````

## Solution #2:

Using @Roland’s definitions:

``````ifelse(is.na(m4) | m4==0, m1+m2+m3, m3+m4)
##      [,1] [,2] [,3]
## [1,]    7    8    8
## [2,]    8    8    7
## [3,]    7    6    8
``````

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .