Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R sqrt() Function - Calculating the Square Root

R sqrt() Function - Calculating the Square Root

R Language Examples R Language Examples

The R sqrt() function is used to calculate the square root of a number.

The square root is a mathematical concept: the square of the square root of a non-negative number equals the original number. In statistics, calculating the standard deviation requires sqrt().

The syntax of the sqrt() function is as follows:

sqrt(x)

Parameter Description:

Example

Calculate the square root of a single number

print

(

sqrt

(

16

)

)

print

(

sqrt

(

2

)

)

Calculate the square root of each element in a vector

x

<-

c

(

4

,

9

,

16

,

25

,

36

)

result.

sqrt

<-

sqrt

(

x

)

print

(

result.

sqrt

)

The output of the code above is:

[1] 4

[1] 1.414214

[1] 2 3 4 5 6

sqrt() is often used when calculating standard deviation, Euclidean distance, and similar:

Example

Manually calculating the standard deviation

x

<-

c

(

2

,

4

,

6

,

8

,

10

)

Step 1: Calculate the mean

m

<-

mean

(

x

)

Step 2: Calculate the variance (the mean of the squared deviations)

variance

<-

sum

(

(

x

m

)

^

2

)

/

(

length

(

x

)

1

)

Step 3: Standard deviation = the square root of the variance

std_dev

<-

sqrt

(

variance

)

print

(

paste

(

"Manual standard deviation:"

, std_dev

)

)

Comparison with the sd() function

print

(

paste

(

"sd() function:"

,

sd

(

x

)

)

)

The output of the code above is:

[1] "手动标准差: 3.16227766016838"

[1] "sd() 函数: 3.16227766016838"

R Language Examples R Language Examples