square root of values in an R vector

Get the Square Root in R using sqrt()

In this tutorial, we will look at how to get the square root for a number (or values in a vector) in R with the help of some examples.

How to get the square root of a number in R?

You can use the built-in math function sqrt() to get the square root (also called the root) of a number in R. Pass the number for which you want to get the square root as an argument to the sqrt() function. The following is the syntax –

sqrt(x)

It returns the square root of the passed number. Note that you can apply the sqrt() function to a numeric vector, array, matrix, and a dataframe as well.

Examples

Let’s look at some examples of using the sqrt() function in R.

Get the square root of a number in R

First, we will apply the sqrt() function directly to a number, for example, 4.

# sq root of 4
print(sqrt(4))

Output:

[1] 2

We get the square root of 4 as 2, which is the correct answer.

Square root of each value in a vector

You can similarly apply the sqrt() function to a numeric vector in R. Note that individual values in R can be regarded as a vector of length one. If you apply the sqrt() function to a numeric vector, it will compute the square root for each value in the vector.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Let’s look at an example.

# sq root of values in a vector
vec <- c(1, 4, 9, 16, 25)
print(sqrt(vec))

Output:

[1] 1 2 3 4 5

You can see that we get a vector with the square root for each value in the passed vector. We get 1, 2, 3, 4, and 5 as the square root values for the numbers 1, 4, 9, 16, and 25 respectively.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Authors

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

  • Gottumukkala Sravan Kumar
Scroll to Top