How to compute summation in r

You need to use sum(), example below:

IndexStart <- 1
x <- seq(IndexStart, 6, 1)
xm <- 1

result1 <- ((x[1]-xm)^2)+((x[2]-xm)^2)+((x[3]-xm)^2)+((x[4]-xm)^2)+((x[5]-xm)^2)+((x[6]-xm)^2)
print(result1)
# [1] 55

result2 <- sum((x-xm)^2) # <- Solution
print(result2)
# [1] 55

Leave a Comment