# 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) |

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 |

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 |

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.

## 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 |

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 |

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 |

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 |

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 combined x3_sqrt # Return output to RStudio console # 3.162278 |

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 |

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 |

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 combined x4_sqrt # Return output to RStudio console # 3.162278 |

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 |

x5 <- factor(10) # Create factor object

…and then let’s apply the sqrt R command to this factor:

sqrt(x5) # Apply sqrt to 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 & sqrt x5_sqrt # Return output to RStudio console # 3.162278 |

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

- The abs Function in R
- Convert Character to Numeric in R
- Convert Factor to Numeric in R
- The R Programming Language

### Subscribe to my free statistics newsletter:

### R Tutorials

abs Function in R

all & any R Functions

Set Aspect Ratio of Plot

attach & detach R Functions

attr, attributes & structure in R

cbind R Command

Change ggplot2 Legend Title

Character to Numeric in R

Check if Object is Defined

col & row sums, means & medians

Complete Cases in R

Concatenate Vector of Strings

Convert Date to Weekday

cumsum R Function

Data Frame Column to Numeric

diff Command in R

difftime R Function

dim Function in R

dir R Function

Disable Scientific Notation

Draw Segments in R

droplevels R Example

Evaluate an Expression

Extract Characters from String

Factor to Numeric in R

Format Decimal Places

get, get0 & mget in R

is.na R Function

is.null Function in R

jitter R Function

Join Data with dplyr Package

length Function in R

lowess R Smoothing Function

max and min Functions in R

NA Omit in R

nchar R Function

ncol Function in R

nrow Function in R

outer Function in R

pairs & ggpairs Plot

parse, deparse & R expression

paste & paste0 Functions in R

pmax and pmin R Functions

polygon Plots in R

pretty R Function

R Find Missing Values

R Functions List (+ Examples)

R NA – Values

R Replace NA with 0

rbind & rbind.fill in R

Read Excel Files in R

readLines, n.readLines & readline

Remove Element from List

Remove Legend in ggplot2

Rename Column Name in R

Replace Last Comma of String

rev R Command

Round Numeric Data in R

Save & Load RData Workspace

scan R Function

setdiff R Function

setNames vs. setnames in R

sink Command in R

Sort, Order & Rank Data in R

sprintf Function in R

Square Root in R

str_c Function of stringr Package

str_sub Function of stringr Package

strptime & strftime Functions

substr & substring R Commands

sweep R Function

Transform Data Frames

union Function in R

unlist in R

weekdays, months, quarters & julian in R

with & within R Functions

Write Excel File in R