Search code examples
rdataframedivide-by-zero

Dividing two data.frame element by element with 0 entries


I have two data.frame and I want to divide them element by element. If the latter has 0-entries the result of the division should be 0. Have you any advice on how to implement it easily? Here df1 is divided by df2 obtaining res.

df1 <- data.frame(a=c(1,4,0),b=c(6,1,2),c=c(0,2,0))
df2 <- data.frame(a=c(0,2,0),b=c(2,1,0),c=c(1,2,6))

res <- data.frame(a=c(0,2,0),b=c(3,1,0),c=c(0,1,0))

Solution

  • We divide the 'df1' by 'df2' and then replace the 'NaN' and 'Inf' values in each column by 0 by looping the columns using lapply.

    res1 <- df1/df2
    res1[] <- lapply(res1, function(x) replace(x, is.infinite(x)|is.nan(x), 0))
    

    Or this can be done by dividing the corresponding columns of 'df1', 'df2' and replacing the 'NaN', 'Inf' within Map

     data.frame(Map(function(x, y) {x1 <- x/y
              ifelse(is.nan(x1)|is.infinite(x1), 0, x1)}, df1, df2))