Calculate running total with condition in R

1731 views r

i want to calculate running total in the column of invested condition is if buy_indicator==BUY and sell_indicator==HOLD then my invested money value should be negative of close_price*100 where 100 is volume of shares which is constant.....else if buy_indicator==HOLD and sell_indicator==SELL then my invested money value should be positive of close_price*100......else buy_indicator==HOLD and sell_indicator==HOLD then it should contain the previous row value....

my dataset looks like this

enter image description here

answered question

Please do not post an image of code/data/error:s it cannot be copied, searched (SEO), breaks screen-readers, and may not fit well on some mobile devices. Ref: If you could please post the output from dput(x) (where x is a not-too-large portion of the data) and whatever code you've tried so far. It also may help (if unclear) what your expected output is given the sample data.

please provide reproducible examples

1 Answer


You can use ifelse to generate the columns with +1 or -1, that you can then multiply by 100*close prices. example:

positiveorneg <- ifelse(buy_indicator==BUY&sell_indicator==HOLD, -1, 1)
moneytoinvest <- positiveorneg*100*closeprice

You can then use cumsum to get the hopefully positively trended line of your money.

mymoney <- cumsum(moneytoinvest)

Don't spend it all in one place.

EDIT: if you have more than one condition you can embed ifelse statements:

ifelse(buy_indicator==BUY&sell_indicator==HOLD, -1, ifelse(buy_indicator==HOLD&sell_indicator==SELL, 1, 0))

posted this

Have an answer?


Please login first before posting an answer.