I want to apply the if else statement to each column (ad) in a data frame, where if each value satisfies a condition based on another column (m), the value remains unchanged, otherwise the value will be changed to zero.
Here is an example of reproducibility:
a <- c(10, 11, 12, 15,7,8)
b <- c(15,11,16,17,1.5,9)
c <- c(18,14,6,14,1,17)
d <- c(12,11,13,19,2,4)
p <- c(2,1,3,2.5,1.3,2.1)
m <- c(12,13,8,9,14,11)
df<- data.frame(a,b,c,d,p,m)
print(df)
a b c d p m
1 10 15.0 18 12 2.0 12
2 11 11.0 14 11 1.0 13
3 12 16.0 6 13 3.0 8
4 15 17.0 14 19 2.5 9
5 7 1.5 1 2 1.3 14
6 8 9.0 17 4 2.1 11
This is the “long” version of what I want to do, which works, but is very repetitive:
df$a<- ifelse((df$a-df$p)>df$m, df$a, 0)
df$b<- ifelse((df$b-df$p)>df$m, df$b, 0)
df$c<- ifelse((df$c-df$p)>df$m, df$c, 0)
df$d<- ifelse((df$d-df$p)>df$m, df$d, 0)
print(df)
This is the result I want:
a b c d p m
1 0 15 18 0 2.0 12
2 11 11 14 11 1.0 7
3 12 16 0 13 3.0 8
4 15 17 14 19 2.5 9
5 0 0 0 0 1.3 14
6 0 0 17 0 2.1 11