Calculate Square in R (4 Examples)
This tutorial shows how to raise the values of a data object to the power of two in the R programming language.
Table of contents:
Let’s dive right in.
Example 1: Compute Square of Single Value
This example illustrates how to calculate the square of a single data value in R.
x <- 5 # Create data object x # Print data object # 5
As you can see based on the previous output of the RStudio console, we’ll use the value 5 for this example.
Now, we can calculate the square of this data object by using the ^ symbol:
x^2 # Calculate square of data object # 25
The RStudio console shows the result: The square of 5 is equal to 25.
Example 2: Compute Square of Vector Using ^
In this example, I’ll illustrate how to raise all elements of a vector to the power of two. First, we have to create a vector in R:
my_vec <- 1:5 # Create vector my_vec # Print vector # 1 2 3 4 5
Now, we can simply apply the ^ symbol to this vector as we already did in Example 1:
my_vec^2 # Calculate square of vector # 1 4 9 16 25
The output is another vector containing the square of each element of our input vector.
Example 3: Compute Square of Vector Using *
This example explains shows an alternative way for the computation of squares in R.
Instead of the ^ symbol, we can also multiply our data by itself by using the * symbol:
my_vec * my_vec # Multiply vector by itself # 1 4 9 16 25
The output is exactly the same as in Example 2.
Example 4: Compute Square of Data Frame
In this example, I’ll show how to take the square of all elements in a numeric data frame. Let’s create some example data:
my_data <- data.frame(x1 = 3:6, # Create data frame x2 = 5:2, x3 = 4) my_data # Print data frame # x1 x2 x3 # 1 3 5 4 # 2 4 4 4 # 3 5 3 4 # 4 6 2 4
Now, we can basically apply the same R code to our data frame as we already did in Examples 1 & 2 (i.e. ^2):
my_data^2 # Calculate square of data frame # x1 x2 x3 # 1 9 25 16 # 2 16 16 16 # 3 25 9 16 # 4 36 4 16
Video, Further Resources & Summary
Do you need further info on the contents of this page? Then I can recommend to watch the following video of my YouTube channel. I’m explaining the R codes of this page in the video tutorial.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, you may read the related tutorials on my website:
Summary: This post illustrated how to take the square of a data object in the R programming language. In case you have further questions, let me know in the comments.
Statistics Globe Newsletter