Irgendniemand Irgendniemand - 2 months ago 10
R Question

Ifelse condition over a mask

I have a problem. Imagine I have a data set a:

row1 row2 row3
col1 2 3 5
col2 5 3 4
col3 3 1 6


And I have a mask, which identifies those entries, which should be transformated:

row1 row2 row3
col1 T F F
col2 F F T
col3 F T F


So basically, I want all of the entries which are labelled as TRUE (T) be replaced by their value they have right now minus the value out of another dataset b:

row1 row2 row3
col1 1 4 8
col2 4 1 1
col3 6 2 7


So the result should be:

row1 row2 row3
col1 1 3 5
col2 5 3 3
col3 3 -1 6


What i tried was:

new_dataset <- ifelse(Mask == 'FALSE', a, a - b)


However, I end up with a list instead of a data frame. I know, that is because R creates every entry within the list by the total dataset a or (a-b). But how can I handle this?

Thank you very much in advance! :)

Answer

You can do a - b * mask:

a - b * mask
#      row1 row2 row3
# col1    1    3    5
# col2    5    3    3
# col3    3   -1    6

It works for both data frames and matrices:

as.data.frame(a) - as.data.frame(b) * as.data.frame(mask)
#      row1 row2 row3
# col1    1    3    5
# col2    5    3    3
# col3    3   -1    6

as.matrix(a) - as.matrix(b) * as.matrix(mask)
#      row1 row2 row3
# col1    1    3    5
# col2    5    3    3
# col3    3   -1    6