Replacing zero values in table A with non-zero values in table B if available

I have data as follows:

tableA <- structure(c(0L, 0L, 6L, 0L, 6L, 0L, 3L, 0L, 0L), dim = c(3L, 
3L), dimnames = structure(list(c("0.3", "0.4", 
"0.6"), c("A", "B", "C")), names = c("", "")), class = "table")

      A B C
  0.3 0 0 3
  0.4 0 6 0
  0.6 6 0 0

tableB <-structure(c(0L, 1L, 2L, 0L, 3L, 0L, 3L, 2L, 0L), dim = c(3L, 
3L), dimnames = structure(list(c("0.3", "0.4", 
"0.6"), c("A", "B", "C")), names = c("", "")), class = "table")

      A B C
  0.3 0 0 3
  0.4 1 3 2
  0.6 2 0 0

I would like to replace all zeroes in tableA with positive values in tableB if they are available and somehow mark them.

What would be the easiest way to achieve this?

Desired output:

      A B C
  0.3 0 0 3
  0.4 1 6 2
  0.6 6 0 0

The added issue is that I would somehow like to know which values were replaced, but that seems difficult to realise.

>Solution :

Create a logical index based on the 0 values in tableA with == and the positive values (> 0) from tableB and do the assignment

i1 <- tableA == 0 & tableB > 0
tableA[i1] <- tableB[i1]

-output

> tableA
     
      A B C
  0.3 0 0 3
  0.4 1 6 2
  0.6 6 0 0

Leave a Reply