There are the following methods to to calculate a square,
- Method 1: Using the ^ operator
- Method 2: Using * operator
- Method 3: Using the sapply() function
Method 1: Using the ^ operator
To calculate the square in R, use the ^ operator or multiply the input value by itself, and you will get the square of the input value.
The ^ is an arithmetic operator used to find the exponent of the vector.
If you have a single integer variable data whose value is 11 and want to find its square, write the following code.
rv <- 11 sqr <- rv ^ 2 sqr
And we got the correct answer, which is indeed 121. This method is a bit faster.
Method 2: Using the * operator
You can also use the multiplication operator in which we will multiply the input value by itself; in our case, it is 11.
rv <- 11 sqr <- rv * 11 sqr
We get the same output.
Calculating the Square of All Values in the R Vector
To calculate the square of all the values of the R Vector, apply the ^ operator to the vector, which returns the vector with squared values. To create a Vector in R, use the c() function.
rv <- c(11, 21, 19, 18, 46) sqrdVec <- rv ^ 2 sqrdVec
 121 441 361 324 2116
You can see that it will return a Vector in which all the elements have been squared.
Method 3: Using the sapply() function
If you encounter a somewhat complicated case, you can use the sapply() function. The sapply() is a built-in R function that applies a function to all the elements of the input Vector or Matrix.
rv <- c(11, 21, 19, 18, 46) sqrdVec <- sapply(rv, function(x) x ^ 2) sqrdVec
 121 441 361 324 2116
How to calculate the Square of the data frame in R
To calculate the square of the data frame in R, use the ^ operator.
df <- data.frame(a1 = 1:3, a2 = 4:6, a3 = 7:9)
To calculate the square of each element of the data frame, use the ^ operator.
df <- data.frame(a1 = 1:3, a2 = 4:6, a3 = 7:9) df ^ 2
a1 a2 a3 1 1 16 49 2 4 25 64 3 9 36 81
To calculate the square of a vector in R, you can use the built-in ^ operator. Apart from the ^ operator, you can also use the * operator and sapply() function.
That is it for this tutorial.
Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.