Reputation: 11
I'm trying to compute a simple summation (to learn how these works on r and then use in a more complicate problem)in r.
This is the summation I'm trying to compute
!(https://i.sstatic.net/9ln8S.jpg)
sum_{i=1}^5 (x^i)
where x
is from 1:5
.
basically the outcome should be either a vector composed like this (sum(1^i),sum(2^i),sum(3^i),sum(4^i),sum(5^i))
so that later I can sum it to get the overall sum
or automatically the sum. (equal to 5699).
The code I've tried to use is the following:
for(i in 1:5){
for(x in 1:5){
a[i] <- sum(x^(i))
}
}
a
however the outcome is this vector
[1] 5 25 125 625 3125
it's only doing the 1^5
,2^5
,3^5
,4^5
,5^5
Any idea of how to do it?
Upvotes: 0
Views: 1665
Reputation: 191
It's certainly best to use built in functions (e.g. sapply, sum) in R because they are optimized and sometimes implemented in faster programming language such as C. For-loops on the other hand run inside R and can be very slow.
The following code should do what you asked for and may be helpful for learning purposes:
# initialize vector
a <- c()
for(x in 1:5) {
# loop through all x
# calculate sum for some x
sum <- 0
for(i in 1:5) {
sum <- sum + x^i
}
# append result to vector a
a <- c(a, sum)
}
print(a)
[1] 5 62 363 1364 3905
sum(a)
[1] 5699
Upvotes: 0
Reputation: 2141
This solves your problem without the need for a for
-loop but the more R-like sapply
vec <- sapply(1:5,function(x) sum(x^(1:5)))
vec
[1] 5 62 363 1364 3905
Sum <- sum(vec)
Sum
[1] 5699
Upvotes: 1