How to Calculate Square of All Values in R Vector

To calculate a square of a single value or a Vector in R, you can use one of the following methods.

  1. Using ^ operator
  2. Using * operator
  3. Using sapply() function

Calculate Square in R

To calculate 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 that is used to find the exponent of the vector.

If you have a single integer variable data whose value is 11 and you want to find the square of it, then 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.

You can also use the multiplication operator in which we will multiply the input value by itself, and in our case, it is 11.

rv <- 11
sqr <- rv * 11
sqr

Output

[1] 121

We get the same output.

Calculate Square of All Values in R Vector

To calculate the square of all the values of 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.

Using sapply() function

If you come across a somewhat complicated case, then 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

Calculate the Square of the data frame

To calculate the square of the data frame in R, use the ^ operator.

To create a data frame, use the data.frame() method.

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

That is it for this tutorial.

See also

Square root in R

Standard deviation in R

Variance in R

Percentile in R

Leave a Comment