Square Root in R (5 Examples) | Apply sqrt Function in R Studio

 

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 R
x1_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 vector
x2_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

 

Warning message: In sqrt(x) : NaNs produced

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 combined
x3_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

 

Error in sqrt(x4) : non-numeric argument to mathematical function

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 combined
x4_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

 

Error in Math.factor(x5) : ‘sqrt’ not meaningful for factors

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 & sqrt
x5_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

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


16 Comments. Leave new

  • 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.

    Reply
    • Hi 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

      Reply
  • 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.

    Reply
    • Hey 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

      Reply
  • (2,3) and (13,8)
    (−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?

    Reply
    • Hi 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

      Reply
  • Hi 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

    Reply
    • Hey 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

      Reply
  • Hi 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?

    Reply
    • Hey 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

      Reply
  • How would I input this into the r?
    5√9

    I’ve tried multiple things but I can’t seem to figure it out.

    HELPPPP

    Reply
  • 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

    Reply
    • Hello,

      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

      Reply
  • Hii, I would like help with a function that sums the square roots of numbers from 1 to 10

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top