[R] Ifelse leading to inconsistent result

Duncan Murdoch murdoch.duncan at gmail.com
Wed Jun 26 18:55:17 CEST 2013


On 26/06/2013 11:40 AM, Neville O'Reilly wrote:
> I have used ifelse in count variables to count the number of times in a simulation the values of a vector of logprice fall within mutually exclusive ranges. However, there is a double count in the result i.e. i am getting output indicating values falling in mutually exclusive ranges. Here is the code and result
> R script
> niter = 1e5 # number of iterations is 10^5
> CountLoss = rep(0,niter)
> CountProf = rep (0,niter)
> set.seed(2009) # enables reproducibility of result if script run again"
> for (i in 1:niter)
> {
>    r = rnorm(100,mean=.05/253,
>              sd=.23/sqrt(253)) # generate 100 random normal numbers
>    logPrice = log(1e6) + cumsum(r) #vector of 100 days log prices
>    maxlogP = max(logPrice) # max price over next 100 days
>    minlogP = min(logPrice)
>    CountLoss[i] <- ifelse (minlogP < log(950000), 1, ifelse (maxlogP > log (1000000), 0, 1))
>    CountProf[i] <- ifelse (maxlogP < log (1100000),0,1)
> }
> sum(CountLoss)
> mean(CountLoss) # fraction of times out of niter that stock is sold for a loss in a 100 day period
> sum(CountProf)
> mean(CountProf) # fraction of times out of niter that stock is sold for a profit in a 100 day period
>
> Output
> sum(CountLoss)
> [1] 64246
> > mean(CountLoss) # fraction of times out of niter that stock is sold for a loss in a 100 day period
> [1] 0.64246
> > sum(CountProf)
> [1] 51857
> > mean(CountProf) # fraction of times out of niter that stock is sold for a profit in a 100 day period
> [1] 0.51857
>
> CountLoss and CountProf should sum to less than the number of interations. When I troubleshoot by reducing the number of iterations and that size of the logprice, I can't reproduce the contradicion.

I don't see a contradiction.  Both CountLoss and CountProf are less than 
niter.  The logic of your test doesn't imply that sum(CountLoss) + 
sum(CountProf) should be less than niter; e.g. a case where minlogP is 
less than log(950000) and maxlogP > log(1100000) would be counted in both.

Duncan Murdoch



More information about the R-help mailing list