3 Easy Ways to Calculate Square in R

There are the following methods to to calculate a square,

  1. Method 1: Using the ^ operator
  2. Method 2: Using * operator
  3. 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

Output

[1] 121

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

Output

[1] 121

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

Output

[1] 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

Output

[1] 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

Output

  a1   a2   a3
1  1   16   49
2  4   25   64
3  9   36   81

Conclusion

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.

See also

Square root in R

Percentile in R

Leave a Comment