LvG - 2 months ago 6
R Question

# Equivalent of '&' for ifelse statements in r

I want to create a new column in a data frame that multiplies three variables together and divides by three others. If the dividing variables equal 0, I want to leave them out. So this is what I was doing:

``````sm3\$mult=ifelse(sm3\$WS==0, (sm3\$RF*sm3\$EF*sm3\$HD/sm3\$M/sm3\$ESF),
ifelse(sm3\$M==0, (sm3\$RF*sm3\$EF*sm3\$HD/sm3\$WS/sm3\$ESF),
ifelse(sm3\$ESF==0,(sm3\$RF*sm3\$EF*sm3\$HD/sm3\$WS/sm3\$M),
(sm3\$RF*sm3\$EF*sm3\$HD/sm3\$WS/sm3\$M/sm3\$ESF))))
``````

But sometimes more than one of the dividing variables equals 0, so if that is the case, I want to leave both out. So I tried this, but it is not working:

``````sm3\$mult=ifelse(sm3\$WS==0, (sm3\$RF*sm3\$EF*sm3\$HD/sm3\$M/sm3\$ESF),
ifelse(sm3\$M==0, (sm3\$RF*sm3\$EF*sm3\$HD/sm3\$WS/sm3\$ESF),
ifelse(sm3\$ESF==0,(sm3\$RF*sm3\$EF*sm3\$HD/sm3\$WS/sm3\$M),
ifelse(sm3\$WS==0 & sm3\$M==0,(sm3\$RF*sm3\$EF*sm3\$HD/sm3\$ESF),
ifelse(sm3\$WS==0 & sm3\$ESF==0,(sm3\$RF*sm3\$EF*sm3\$HD/sm3\$M),
ifelse(sm3\$M==0 & sm3\$ESF==0,(sm3\$RF*sm3\$EF*sm3\$HD/sm3\$WS),
ifelse(sm3\$WS==0 & sm3\$M==0 & sm3\$WS==0,(sm3\$RF*sm3\$EF*sm3\$HD),
(sm3\$RF*sm3\$EF*sm3\$HD/sm3\$WS/sm3\$M/sm3\$ESF))))))))
``````

No errors come up, it just spits out the same output as the one above (which is not what I want).

There is probably a much easier way to do this (which I would love to hear about), but I also want to know why '&' doesn't work and if there is anything that works instead. Lots of googling hasn't turned up anything useful. Thank you very much

Take the dividing columns and convert all 0s to 1s

For example, if you have this data frame

``````a = c(2,3,4,0)
b = c(5,0,2,1)
c = c(0,4,2,3)

d = data.frame(a,b,c)

> d
a b c
1 2 5 0
2 3 0 4
3 4 2 2
4 0 1 3
``````

and you want to divide `a` by `b` and `c` replace all zeros in b and c by 1

``````d\$b[d\$b==0] = 1
d\$c[d\$c==0] = 1

d\$e = d\$a/d\$b/d\$c
``````

Result:

``````> d
a b c    e
1 2 5 1 0.40
2 3 1 4 0.75
3 4 2 2 1.00
4 0 1 3 0.00
``````

If you don't want to modify your columns make a copy of them, do the substitution and then erase the copies.

Source (Stackoverflow)