 Bhail -4 years ago 93
R Question

# Summation of a sequence

If n(1) = 1 ,n(2) = 5, n(3) = 13, n(4) = 25, ...
I am using a for loop for summation of these terms

`1 + (1*4 - 4) + (2*4 - 4) + (3*4 - 4) + ..`

This is the function I am using with a for loop:

``````shapeArea <- function(n) {

terms <- as.numeric(1)
for(i in 1:n){
terms <- append(terms, (i*4 - 4))
}
sum(terms)
}
``````

This works fine (as shown here):

``````> shapeArea(3)
 13
> shapeArea(2)
 5
> shapeArea(4)
 25
``````

Yet I was also thinking how can I do this without saving the terms of the series in numeric vector
`terms`
. In other words is there a way to find summations of terms without saving them in a vector first. Or is this the efficient way to do this.

Thanks Ronak Shah
Answer Source

You can change your `shapeArea` function to a one-liner

``````shapeArea <- function(num) {
1 + sum(seq(num) * 4) - (4 * num)
}

shapeArea(1)
# 1
shapeArea(2)
# 5
shapeArea(3)
# 13
shapeArea(4)
# 25
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download
Latest added