How do I best create a function to perform the following sums [closed]
For a sequence of numbers x, how do I best create a function S(x, r, s)
that computes sum(x[t]*x[t+r-s]
, where t
ranges from s
to length(x)-r+1
and r,s > 0
.
You might want to enforce a relationship between the length of x, and the values of s and r as well, or you can end up with some strange results. Try 6:1 for instance.
sumfunc <- function(x, s, r) {
s <- s[s>0]
r <- r[r>0]
if(!(length(r)==1 && length(s)==1)) stop("s and r should be numbers > 0")
t <- s:(length(x)-r+1)
return(sum(x[t]*x[t+r-s]))
}
精彩评论