3
$\begingroup$

How can I calculate Standard Deviation, step-by-step, in R? Thanks!

$\endgroup$

closed as off-topic by John, shadowtalker, Christoph Hanck, kjetil b halvorsen, gung Sep 11 '15 at 6:58

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question appears to be off-topic because EITHER it is not about statistics, machine learning, data analysis, data mining, or data visualization, OR it focuses on programming, debugging, or performing routine operations within a statistical computing platform. If the latter, you could try the support links we maintain." – shadowtalker, Christoph Hanck, kjetil b halvorsen, gung
If this question can be reworded to fit the rules in the help center, please edit the question.

  • $\begingroup$ Do you know the formula for standard deviation? Can you elaborate on 'step by step'? $\endgroup$ – rightskewed Sep 11 '15 at 2:46
  • $\begingroup$ Hi! Yes, I believe do! I'm trying to calculate sd for a specific data set. I am aware that I can simply use the sd function, but I need to calculate the standard deviation of a data set "by hand," using R. These are the values: [1] 179 160 136 227 217 168 108 124 143 140 309 229 181 141 260 203 148 169 213 257 244 [22] 271 243 230 248 327 329 250 193 271 316 267 199 171 158 248 423 340 392 339 341 226 [43] 320 295 334 322 297 318 325 257 303 315 380 153 263 242 206 344 258 368 390 379 260 [64] 404 318 352 359 216 222 283 332 Thank you! $\endgroup$ – Tessa Sep 11 '15 at 2:56
  • 2
    $\begingroup$ $variance = \frac{sum((x-mean(x))^2)}{(length(x)-1)}$ $\endgroup$ – rightskewed Sep 11 '15 at 3:07
10
$\begingroup$
> a <- c(179,160,136,227)
> sd(a)
[1] 38.57892
> sqrt(sum((a-mean(a))^2/(length(a)-1)))
[1] 38.57892

```

$\endgroup$
2
$\begingroup$

So, you want to calculate the standard deviation step-by-step. So, firstly, you should calculate the sum of the differences of all data points with the mean.

Have a variable called count and set it to the value 0.

For that, you loop through the data set with a variable, say i and subtract i every time with the mean. Mean can be calculated as mean(dataset).

Add the result of every loop iteration to count, by count = count + (i-mean)^2

Now, divide the count variable by len(dataset) - 1

The result is the variance. So, for calculating the standard deviation, you have to square root the above value.

In R, you do this as: sqrt(variance)

Finally, the result you get after applying the square root is the Standard Deviation.

$\endgroup$
  • 2
    $\begingroup$ "+=" is not an operator in R $\endgroup$ – Glen_b Sep 12 '15 at 5:55
  • $\begingroup$ Glen_b Thank you. Edit done. Was going with the pseudo algo format. $\endgroup$ – Dawny33 Sep 12 '15 at 6:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.