To calculate a square of a single value or a Vector in R, you can use one of the following methods.
- Using ^ operator
- Using * operator
- 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
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
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
 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
 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
a1 a2 a3 1 1 16 49 2 4 25 64 3 9 36 81
That is it for this tutorial.
Krunal Lathiya is an Information Technology Engineer by education and web developer by profession. He has worked with many back-end platforms, including Node.js, PHP, and Python. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language. Krunal has written many programming blogs, which showcases his vast expertise in this field.