How to Use the Square Root Function in R (With Examples)


You can use the sqrt() function to find the square root of a numeric value in R:

sqrt(x)

The following examples show how to use this function in practice.

Example 1: Calculate Square Root of a Single Value

The following code shows how to calculate the square root of a single value in R:

#define x
x <- 25

#find square root of x
sqrt(x)

[1] 5

Example 2: Calculate Square Root of Values in Vector

The following code shows how to calculate the square root of every value in a vector in R:

#define vector
x <- c(1, 3, 4, 6, 9, 14, 16, 25)

#find square root of every value in vector
sqrt(x)

[1] 1.000000 1.732051 2.000000 2.449490 3.000000 3.741657 4.000000 5.000000

Note that if there are negative values in the vector, there will be a warning message. To avoid this warning message, you can first convert each value in the vector to an absolute value:

#define vector with some negative values
x <- c(1, 3, 4, 6, -9, 14, -16, 25)

#attempt to find square root of each value in vector
sqrt(x)

[1] 1.000000 1.732051 2.000000 2.449490      NaN 3.741657      NaN 5.000000
Warning message:
In sqrt(x) : NaNs produced

#convert each value to absolute value and then find square root of each value
sqrt(abs(x))

[1] 1.000000 1.732051 2.000000 2.449490 3.000000 3.741657 4.000000 5.000000

Example 3: Calculate Square Root of Column in Data Frame

The following code shows how to calculate the square root of a single column in a data frame:

#create data frame
data <- data.frame(a=c(1, 3, 4, 6, 8, 9),
                   b=c(7, 8, 8, 7, 13, 16),
                   c=c(11, 13, 13, 18, 19, 22),
                   d=c(12, 16, 18, 22, 29, 38))

#find square root of values in column a
sqrt(data$a)

[1] 1.000000 1.732051 2.000000 2.449490 2.828427 3.000000

Example 4: Calculate Square Root of Several Columns in Data Frame

The following code shows how to use the apply() function to calculate the square root of several columns in a data frame:

#create data frame
data <- data.frame(a=c(1, 3, 4, 6, 8, 9),
                   b=c(7, 8, 8, 7, 13, 16),
                   c=c(11, 13, 13, 18, 19, 22),
                   d=c(12, 16, 18, 22, 29, 38))

#find square root of values in columns a, b, and d
apply(data[ , c('a', 'b', 'd')], 2, sqrt)

            a        b        d
[1,] 1.000000 2.645751 3.464102
[2,] 1.732051 2.828427 4.000000
[3,] 2.000000 2.828427 4.242641
[4,] 2.449490 2.645751 4.690416
[5,] 2.828427 3.605551 5.385165
[6,] 3.000000 4.000000 6.164414

Additional Resources

How to Transform Data in R (Log, Square Root, Cube Root)
How to Calculate Root Mean Square Error (RMSE) in R

Leave a Reply

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