i am trying to run a simple multiplication of a data.frame column with a scalar A respectively scalar B based on the value of third column (id) of the same data.frame. Somehow I have some (order,sort?) problem – so far the result is definitely wrong. Here are several tries:
mydf$result = subset(mydf,myid==123,multiplyme)*0.6 +
subset(mydf,myid==124,,multiplyme)*0.4
I also tried to use %in% syntax but was not successful either. I know I could MySQL for example and connect to R, but in this case I just want to use (basic) R or plyr at least here. Just for those of you who prefer code over my blabla, here´s how i´d do it in SQL:
SELECT
MIN(CASE WHEN myid=123 THEN multiplyme*0.6 END)
MIN(CASE WHEN myid=124 THEN multiplyme*0.4 END)
FROM mytable
GROUP BY result;
Thx for any help / R-code suggestions in advance!
Please note that I have more than 2 ids!
Assuming you only have 123 or 124 in
myid:If you have other variables in
myidadd an extraifelseand a default case.EDIT:
Since you have extra variables in
myid, I’ll state the expansion.You can change the 0 at the end to a 1 if in the defualt case you want to keep the value of
multiplyme. This can be extended into a chain ofifelsestatements if you want to use a different multiple for many values.However, as mbq comments below, you can use a
switchstatement if it begins to get unwieldy:This would probably be slower though, as this will loop while
ifelseis vectorised.