[R] Replace for loop when vector calling itself

David Winsemius dwinsemius at comcast.net
Mon Mar 7 14:35:56 CET 2011


On Mar 7, 2011, at 12:34 AM, rivercode wrote:

> Hi,
>
> I am missing something obvious.
>
> Need to create vector as:
>
> (0, i-1 + TheoP(i) - TheoP(i-1), repeat....) Where i is the index  
> position
> in the vector and i[1] is always 0.

I think your prototype is not agreeing with the code below. Is "i"  
suppose to be the index (as suggested above) or the prior term (as  
implied below)?
>
> Found myself having to use a For Loop because I could not get sapply
> working.   Any suggestions ?

Assuming the code below, you construct the first three or four values  
by hand I think you will find that the intermediate values of TheoP  
will have alternating signs.

term2 = 2-1 + TheoP(2) - TheoP(1)
term3 = 3-1 + TheoP(3) - (2-1 + TheoP(2) - TheoP(1))
term4 = 4-1 + TheoP(4) - (3-1 + TheoP(3) - (2-1 + TheoP(2) - TheoP(1)) )

The answer to the first question will determine how you proceed. If  
the index is being used then there are two series of cumulative sums  
and perhaps you can construct an expression that can be fed to the  
cumsum function.

The diff function is also available and if the index version is  
correct, then it might even be as simple as c(0,  
((1:len)-1)+diff(TheoP) )

So clarify what is intended.
-- 
David.

>
> delta <- function(x) {
>
> 	start = index[x]
> 	end = index[x+1] - 1
> 	iTheo = start:end
> 	len = length(iTheo)
> 	theoP = as.numeric(TheoBA$Bid[iTheo])
> 	d = vector(mode = "numeric", length= len)
> 	d[1] = 0
> 	if (len>1) for (i in 2:len) { d[i] = d[i-1] + theoP[i] - theoP[i-1] }
> 	return(d)
> }
>
> Thanks,
> Chris
>
> --


David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list