How to Compute Summation in R

My R code:

((x[1]-xm)^2)+((x[2]-xm)^2)+((x[3]-xm)^2)+((x[4]-xm)^2)+((x[5]-xm)^2)+((x[6]-xm)^2)

This computation would be much easier if i formulated the problem as a summation. How do I do that in r? Something like:

sum((x[i]-xm)^2) for i=1 to i=6?

x is a data frame.

6

2 Answers

Without reading all the responses in this thread, there is a really easy way to do summations in R.

Modify the following two lines as needed to accommodate a matrix or other type of vector:

i <- 0:5; sum(i^2)

Use i for your index when accessing a position in your vector/array.

Note that i can be any vector.

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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest