In this tutorial, I’m going to show you how to calculate the square root in R. The tutorial is mainly based on the sqrt function:
Basic R Syntax:
sqrt(x)
Definition:
The sqrt R function computes the square root of a numeric data object.
In the following article, I’ll show you five examples for the application of sqrt in the R programming language. Examples 1 and 2 illustrate the basic application of sqrt and Examples 3, 4, and 5 show some typical warnings and errors that can occur when sqrt is applied in a wrong way.
So without further ado, let’s get started!
Example 1: Calculate Square Root of Numeric Value in R
In the first example, I’m going to apply the sqrt function to a single numeric value. Let’s first create such a numeric data object:
x1 <- 16 # Data object containing numeric value
The exemplifying data object contains the value 16. Now, we can apply the sqrt R function to this numeric data object:
x1_sqrt <- sqrt(x1) # Apply sqrt to numeric value in Rx1_sqrt # Return output to RStudio console# 4
That’s it! The square root of 16 is equal to 4.
By the way: I have recently published a video, which explains the R programming code of Example 1 and the R programming code of Example 2 in more detail. Check out the video here:
Example 2: Apply sqrt Function to Vector
We can also apply the sqrt command to a numeric vector. Let’s create such a vector:
x2 <- c(5, 9, 12, 20, 3) # Create numeric vector
For a vector, we can use the same R code as in Example 1:
x2_sqrt <- sqrt(x2) # Apply sqrt to vectorx2_sqrt # Return output to RStudio console# 2.236068 3.000000 3.464102 4.472136 1.732051
2.236068 is the square root of 5; 3.000000 is the square root of 9; and so on…
Of cause we could also apply the sqrt function to a variable or column that is stored in a data.frame or matrix.
So far so good, but sometimes there might occur errors and warnings. In the following three examples, I’m going to show you which problems can appear and how to handle these problems.
Example 3: Warning message: In sqrt(x) : NaNs produced
A warning that occurs commonly is the following:
Warning message: In sqrt(x) : NaNs produced
This warning message pops up, whenever we try to calculate the square root of a negative value. Let’s do an example:
x3 <- - 10 # Negative value
When we try to calculate the square root of – 10, the following warning message is returned to the R Studio console:
sqrt(x3) # Apply sqrt to negative value
Figure 1: Warning message: In sqrt(x) : NaNs produced.
One way to solve this issue is the combination of the abs function with the sqrt function, i.e. converting the negative value to its absolute value before applying sqrt:
x3_sqrt <- sqrt(abs(x3)) # Apply abs & sqrt combinedx3_sqrt # Return output to RStudio console# 3.162278
However, it needs to be evaluated carefully whether this makes sense in your specific situation.
Example 4: Error in sqrt(x) : non-numeric argument to mathematical function
Even worse: Sometimes the sqrt function returns an error message:
Error in sqrt(x) : non-numeric argument to mathematical function
This error occurs, whenever we try to calculate the square root of a character string. Consider the following example character:
x4 <- "10" # Create character object
If we apply the sqrt function to this character object, the R Studio console returns the following:
sqrt(x4) # Apply sqrt to character
Figure 2: Error in sqrt(x) : non-numeric argument to mathematical function.
The solution? Just convert this character to numeric before computing the square root:
x4_sqrt <- sqrt(as.numeric(x4)) # Apply as.numeric & sqrt combinedx4_sqrt # Return output to RStudio console# 3.162278
Example 5: Error in Math.factor(x5) : ‘sqrt’ not meaningful for factors
A similar error appears when we try to compute the square root of data with the factor class:
Error in Math.factor(x5) : ‘sqrt’ not meaningful for factors
Let’s try that in practice. First, let’s create a factor…
x5 <- factor(10) # Create factor object
…and then let’s apply the sqrt R command to this factor:
sqrt(x5) # Apply sqrt to factor
Figure 3: Error in Math.factor(x5) : ‘sqrt’ not meaningful for factors.
As expected: we get an error message. However, we can solve this issue simply by converting the factor to numeric:
x5_sqrt <- sqrt(as.numeric(as.character(x5))) # as.numeric, as.character & sqrtx5_sqrt # Return output to RStudio console# 3.162278
Video Tutorial: Manual Computation of the Square Root
In this R tutorial, we learned a lot about the programming routines that we can apply when calculating a square root. However, we have not learned much about the mathematical background itself. In case you want to learn more about the mathematics behind the square root, I can recommend the following video of the tecmath YouTube channel. The video explains some simple math tricks for the manual computation of the square root.
Further Reading
- The abs Function in R
- Convert Character to Numeric in R
- Convert Factor to Numeric in R
- The R Programming Language
16 Comments. Leave new
Tim
September 16, 2020 1:32 am
I’m trying to figure out the following: Obtain the average for the square root of all multiples for even numbers from 2-100. Compute the square root of all even numbers from 2-100, and then average them.
ReplyJoachim
September 16, 2020 6:39 am
ReplyHi Tim,
I’m not sure if this is exactly what you are asking for, but how about something like this?
x <- seq(2, 100, 2)x_sqrt <- sqrt(x)x_sqrt_mean <- mean(x_sqrt)x_sqrt_mean# 6.760953
Regards,
Joachim
raman
June 4, 2021 6:26 am
I’m trying to figure out :a function to calculate square root of a given number only if the input is numeric else give an error.
ReplyJoachim
June 4, 2021 6:36 am
ReplyHey Raman,
You may create your own function for this:
my_sqrt <- function(x) { if(is.numeric(x)) { sqrt(x) } else { "Not numeric!" }}my_sqrt(5)my_sqrt("string")
I hope that helps!
Joachim
Reco
June 28, 2021 4:19 am
(2,3) and (13,8)
Reply
(−4,−1) and (7,−3)
(7/3,1/5) and (1/3,6/5)
(2√3,√6) and (−3√,5√6)
Hello. I’m calculating the distance between two points. How do I enter a square root number into the formula? Also, what command would I use for R to calculate the formula once i’ve entered it?Joachim
June 28, 2021 6:34 am
ReplyHi Reco,
As explained in this tutorial, you would have to use the sqrt function (i.e. sqrt(3)). After specifying your formula, you can use Ctrl + Enter to execute your code.
Regards
Joachim
Derek James
November 12, 2021 10:24 am
ReplyHi Joachim,
Maybe this is not exactly what you are trying to do but I’m trying to do the following math problem in R.
What could be the most beneficial way of doing this?((√120 × 16) ÷ 2) × 100
Joachim
November 13, 2021 9:49 am
ReplyHey Derek,
You would simply have to replace the mathematical operators by their corresponding functions and operators in R:
((sqrt(120) * 16) / 2) * 100
Regards,
Joachim
KD
April 6, 2022 2:06 pm
ReplyHi Joachim,
I’m going to make a function that calculates the square root, and the result has to be printed as a vector What should I do?
Joachim
April 7, 2022 8:54 am
ReplyHey KD,
What would be the difference of this function compared to the sqrt function?
Could you give an example of input data and the required output?
Regards,
Joachim
Nic
April 17, 2022 4:28 am
ReplyHow would I input this into the r?
5√9I’ve tried multiple things but I can’t seem to figure it out.
HELPPPP
Joachim
April 18, 2022 8:53 am
ReplyHey Nic,
Are you looking for this?
5 * sqrt(9)# [1] 15
Regards,
Joachim
Lovemore Kunorozva
April 18, 2023 6:24 pm
I would like to create an R command that still gives the answer of a negative value say sir of -9 instead of the answer being 3. I want the answer to be nagative 3. I have a huge dataset that I need to use for genetic correlation and some of the values are negative and I would like to maintain the sign after performing the sqrt function. any help I can get would be greatly appreciated
ReplyCansu (Statistics Globe)
April 19, 2023 9:09 am
ReplyHello,
Could something like this help?
data<-data.frame(num=c(5, -9, -12, 20, 3))data$sqrt<-sqrt(abs(data$num))data$signed_sqrt<-ifelse(data$num<0, data$sqrt*-1, data$sqrt)data# num sqrt signed_sqrt# 1 5 2.236068 2.236068# 2 -9 3.000000 -3.000000# 3 -12 3.464102 -3.464102# 4 20 4.472136 4.472136# 5 3 1.732051 1.732051
Regards,
Cansu
Harrison
July 24, 2023 6:41 am
Hii, I would like help with a function that sums the square roots of numbers from 1 to 10
ReplyCansu (Statistics Globe)
August 7, 2023 2:49 pm
ReplyHello Harrison,
You can use the sum function in addition to sqrt to accomplish this. See the code below:
numbers <- 1:10sum_of_roots <- sum(sqrt(numbers))sum_of_roots
Best,
Cansu
Leave a Reply
I’m Joachim Schork. On this website, I provide statistics tutorials as well as code in Python and R programming.
Statistics Globe Newsletter
Related Tutorials
Calculate Sum of Squared Deviations in R (2 Examples)