# How to do sequential calculation referencing previous row value in the same vector/column

Note: I'm a beginner but I'm trying to switch from excel to R doing some backtesting for a trading strategy. I'm having a data.frame with vectors of prices, indicator signal (Buy/Sell), etc.

What I need to do is to have a new sequential vector or "column" (actually a number of them), which is always going to (as part of a nested ifelse) also look at the previous row to determine the correct response and/or it's going to copy the value from its previous row if a condition is met.

One of the nested ifelse should work more or less in this fashion (sorry for the excel-type logic):
my_data\$Status <- ifelse(the value in previous row is any of three values (0,"Buy","Sell), my_data\$MTM,
ifelse(my_data\$MTM== 0, 0,
ifelse(my_data\$MTM<= variable1, "TP",
ifelse(my_data\$MTM=>variable2, "SL",0)
)
)
)

I can actually get it done through the "for loop" mechanism but it doesn't help my speed issues which I'm having with excel (actually this takes more time now with R)...

I'm receiving various errors, probably because the first row in such a function is referencing to the header, or that the new vector is being built using "itself" so it cannot even be started and throws a logical error...

Thanks a million for any help!

Yeah, I know this function, but it doesn’t work for me (yet) for the reasons I stated (vector referencing to self prior to being built, or vector referencing to the header on “row 1”).

If you want to check for one of three conditions then you should prefer case_when function to ifelse.
If you want someone to try their hand at processing your data you should consider providing a sample of your data.

``dput(head(mydata,n=10))``

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.