Delto
Delto

Reputation: 331

For Loop in R - Need Assistance

I'm struggling with For Loops and hope that someone can assist me. I need use a loop in R to determine the value of Σ25i=1i2

enter image description here

I'm new to learning R, and I can't seem to figure this out.

Thank you for your help.

Upvotes: 0

Views: 530

Answers (3)

AlexB
AlexB

Reputation: 3269

R is vectorized, therefore a loop is not the natural way of doing this computation. Better to perform the sum this way:

sum(seq(1, 25, 1)^2)

#5525

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101343

A faster way for calculation with larger n is to apply the math formula

res <- n*(n+1)*(2n+1)/6

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

With a for loop you can do :

n <- 25
vec <- numeric(n)
for(i in seq_len(n)) vec[i] <- i^2
sum(vec)
#[1] 5525

seq_len creates a sequence from 1 to n and for each value we square the number and store it in vec at ith positon.


However, you can do this without for loop directly.

sum(seq_len(n)^2)
#[1] 5525

Upvotes: 4

Related Questions