Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compute summation in r

Tags:

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.

like image 289
econmajorr Avatar asked Apr 28 '16 19:04

econmajorr


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.

like image 123
Mark McDonald Avatar answered Nov 14 '22 23:11

Mark McDonald


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
like image 31
Technophobe01 Avatar answered Nov 14 '22 23:11

Technophobe01