Calculate Sum of Squared Deviations in R (2 Examples)
Table of contents:
Let’s get started.
Consider the following example data:
x <- 11:20 # Create example vector x # Print example vector #  11 12 13 14 15 16 17 18 19 20
The previous output of the RStudio console shows that our example data is a numeric vector containing a range from 11 to 20.
Example 1: Compute Sum of Squares Using sum() & mean() Functions
The following R programming syntax illustrates how to calculate the sum of squared deviations of a numeric vector in R.
ss_1 <- sum((x - mean(x))^2) # Calculate sum of squares ss_1 # Print sum of squares #  82.5
The previous output of the RStudio console shows the result: The sum of squares of our input vector is 82.5.
Example 2: Compute Sum of Squares Using var() & length() Functions
Have a look at the following R code:
ss_2 <- var(x) * (length(x) - 1) # Calculate sum of squares ss_2 # Print sum of squares #  82.5
As you can see, the RStudio console returns exactly the same result as the code in Example 1. For that reason, the code of Example 2 provides a good way to double-check your results.
Video, Further Resources & Summary
In case you need more explanations on the R programming codes of this tutorial, you may want to have a look at the following video on the Statistics Globe YouTube channel. In the video, I’m explaining the R code of this article in a live session:
Furthermore, you may have a look at some of the related articles on statisticsglobe.com. You can find a selection of tutorials below.
- Calculate (Root) Mean Squared Error
- Calculate Moving Average, Maximum, Median & Sum of Time Series
- Calculate Sum & Mean of Hours, Minutes & Seconds
- Introduction to R Programming
In summary: You have learned on this page how to calculate the sum of squared deviations in the R programming language. Let me know in the comments section, in case you have additional questions.