How to do a cumulative sum inverse square weighting based upon how many items you want to calculate off a vector in R?

Viewed 24

Suppose I have a vector of length 10

vec <- c(10,9,8,7,6,5,4,3,2,1)

and I wanted to create a function that takes in a subset length value (say 3) and computes the squared inverse up to that length. I would like to compute:

10+(9/(2^2))+(8/(3^2))

which would be

vec[1]+(vec[2]/(2^2))+(vec[3]/(3^2))

but with a function that can take input of the subset length.

The only solution I can think of is a for loop, is there a faster more elegant solution in R?

1 Answers

Yes, you can use the fact that most operations in R are vectorised to do this without a loop:

vec <- c(10,9,8,7,6,5,4,3,2,1)

cum_inverse_square  <- function(vec, n) {
    sum(vec[1:n] / (1:n)^2)
}

cum_inverse_square(vec, 3) == 10+(9/(2^2))+(8/(3^2)) # TRUE
Related