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.
CodePudding user response:
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
CodePudding user response:
We can use !tableA
as a mask like below
> (!tableA) * tableB tableA
A B C
0.3 0 0 3
0.4 1 6 2
0.6 6 0 0
CodePudding user response:
Another possible solution:
ifelse(tableA == 0, pmax(tableB,0), tableA)
#>
#> A B C
#> 0.3 0 0 3
#> 0.4 1 6 2
#> 0.6 6 0 0
CodePudding user response:
another approach
ifelse(tableA == 0 & tableB > 0 , tableB , tableA)