R sqrt() Function - Calculating the Square Root
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:
-
x A number or numeric vector as input; must be non-negative (negative values return NaN).
Example
Calculate the square root of a single number
(
sqrt
(
16
)
)
(
sqrt
(
2
)
)
Calculate the square root of each element in a vector
x
<-
c
(
4
,
9
,
16
,
25
,
36
)
result.
sqrt
<-
sqrt
(
x
)
(
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
)
(
paste
(
"Manual standard deviation:"
, std_dev
)
)
Comparison with the sd() function
(
paste
(
"sd() function:"
,
sd
(
x
)
)
)
The output of the code above is:
[1] "手动标准差: 3.16227766016838"
[1] "sd() 函数: 3.16227766016838"
R Language Examples