11

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.

Frank
  • 66,179
  • 8
  • 96
  • 180
econmajorr
  • 291
  • 1
  • 4
  • 10
  • You should provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input data and desired output. If `x` is a data.frame it seems odd that this would work with `x[1]` and not `x[[1]]`. Are you sure `x` isn't a vector? – MrFlick Apr 28 '16 at 19:43
  • 2
    This might help you http://stackoverflow.com/questions/21385377/calculating-sum-of-squared-deviations-in-r – Gaurav Taneja Apr 28 '16 at 19:45
  • I would suggest you use loops. Your example is rather simple, so i would follow the instructions in this link and i think you will get your answer in no time! good luck. [link] (http://www.r-bloggers.com/how-to-write-the-first-for-loop-in-r/) – Dfinzgar Apr 28 '16 at 19:55
  • 3
    @Dfinzgar loops are a terrible recommendation for this problem. All basic arithmetic is vectorized in R, so `sum((x-xm)^2)` works perfectly as Technophobe01 demonstrates. – Gregor Thomas Apr 28 '16 at 20:02
  • 1
    You say `x` is a data frame, which makes your question less clear. That implies that `x[i]` is a column vector, so the question is what do you mean to sum column vectors? Do you want the overall sum? The row sums? Something else? A small reproducible example with sample data (preferably shared via simulation or `dput()`) makes everything clear. [See here for tips on asking good reproducible R questions.](http://stackoverflow.com/q/5963269/903061) – Gregor Thomas Apr 28 '16 at 20:06
  • @Gregor I tried loops and you are right :) Thanks. – Dfinzgar Apr 28 '16 at 20:22

2 Answers2

14

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.

Patrick
  • 5,526
  • 14
  • 64
  • 101
Mark McDonald
  • 151
  • 1
  • 4
12

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
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
Technophobe01
  • 8,212
  • 3
  • 32
  • 59