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...
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.
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