Reputation: 23
Basically, I have
x<-rnorm(5)
.
I write a vector which takes integers 1 <= n <= 5
then returns in a vector the result from the series (1/n) * sum_{i=1}^n (1/x_i)
so
n=1 -> 1 * 1/x_1
n=2 -> (1/2) * ( 1/(x_1 + x_2) )
n=3 -> (1/3) * ( 1/(x_1 + x_2 + x_3) )
n=4 -> (1/4) * ( 1/(x_1 + x_2 + x_3 + x_4) )
I wrote this function:
series <- function(n){
n=seq(1,5,1)
x<-rnorm(length(n))
print(x)
return ( (1/n)* (1/sum(x[1:length(x[n])])) )
}
But the result is not true, for example
> series(5)
[1] 1.17810059 0.85472777 -0.55077392 -0.03856963 -0.19404827
[1] 0.8003608 0.4001804 0.2667869 0.2000902 0.1600722
for n=2 -> 1/2 * 1/x_1 + 1/x_2 = (1/2) * (1/(1.17810059+ 0.85472777))
but unfortunately, the result according to my code is 0.4001804
!
P.S: I want to write the code without loops and without any function needs calling a library! just to define a simple function using the basic known functions in R and then I can save the result, if needed using Vectorize()
or outer()
Upvotes: 2
Views: 67
Reputation: 39858
Building on the basic idea from @MrFlick, you can also do:
1/seq_along(x) * 1/cumsum(x)
[1] -1.7841988 -0.6323886 0.4339966 0.2981289 0.2066433
Upvotes: 1
Reputation: 206167
The sum()
function is not vectorized. It collapsing everything down to a single value. instead, you can use cumsum()
to get the cumulative some of all the values in the vector thus far.
series <- function(n){
n <- seq(1,5,1)
x <- rnorm(length(n))
print(x)
return((1/n)* (1/cumsum(x)))
}
Upvotes: 1