I am trying to create a conditional sum to calculate the average value. The idea is that the function (or the apply operator) checks if a certain value is true (for example, x> 0), then sums all the values of x, where it is greater than zero. The final step would be to divide this amount by the number of instances that are greater than zero. The search for conditonal sum (ming) did not give me useful information.
This is a piece of data:
> tmpData Instrument TradeResult.Currency. 1 JPM -3 2 JPM 264 3 JPM 284 4 JPM 69 5 JPM 283 11 KFT -8 12 KFT -48 13 KFT 125 14 KFT -150 15 KFT -206 16 KFT 107
Of the features I tried, the most promising is the following:
avgProfit <- function(x) { ifelse(x > 0, sum(x) / length(which(x > 0)), return(0)) }
However, the output of this function is 0:
> with(tmpData, tapply(TradeResult.Currency., Instrument, avgProfit)) JPM KFT 0 0 > avgProfit(tmpData$TradeResult.Currency.) [1] 0 > x [1] 1 1 2 1 2 3 3 3 4 4
(Values should be 225 for JPM (a total of 900 divided into 4 instances, where more than zero) and 116 for KFT)
Despite the fact that I calculate the sum of x (which, if I understand correctly, should be the sum of the individual values in data.frame) in the function, the output of the variable "x" puzzles me. I can’t find where these 1,2,3 and four come from.
How can I calculate the notional amount? Also, do I need to use the function, or am I making it too complicated (maybe there is a built-in R function for this that I missed?)
Any thoughts are more than welcome.
Hello,