R sd() Function - Computing Standard Deviation
The R sd() function is used to compute the standard deviation of a sample.
The standard deviation measures the dispersion of data; a larger value means the data is more spread out. It is the positive square root of the variance.
The syntax of the sd() function is as follows:
sd(x, na.rm = FALSE)
Parameter Description:
-
x Input numeric vector.
-
na.rm A boolean value, default FALSE, sets whether to remove missing values NA.
Example
Two datasets with the same mean but different standard deviations
group1
<-
c
(
85
,
86
,
84
,
85
,
86
,
84
,
85
,
85
)
group2
<-
c
(
60
,
70
,
85
,
90
,
95
,
100
,
75
,
105
)
Compute the mean and standard deviation
(
paste
(
"Group 1 - mean:"
,
mean
(
group1
)
,
"Standard deviation:"
,
sd
(
group1
)
)
)
(
paste
(
"Group 2 - mean:"
,
mean
(
group2
)
,
"Standard deviation:"
,
sd
(
group2
)
)
)
The output of the code above is:
[1] "第一组 - 均值: 85 标准差: 0.925820099772551"
[1] "第二组 - 均值: 85 标准差: 15.1186472433265"
The standard deviation is often used for probability estimation in normal distributions. About 68% of data falls within +/-1 standard deviation of the mean:
Example
Generate normally distributed data
set.seed
(
123
)
scores
<-
rnorm
(
1000
,
mean
=
70
,
sd
=
10
)
Compute the mean and standard deviation
m
<-
mean
(
scores
)
s
<-
sd
(
scores
)
Compute the proportion within +/-1 standard deviation
within_1sd
<-
mean
(
scores
=
m
s
&
scores
<=
m
s
)
(
paste
(
"Mean:"
,
round
(
m,
2
)
)
)
(
paste
(
"Standard deviation:"
,
round
(
s,
2
)
)
)
(
paste
(
"Proportion within +/-1 standard deviation:"
,
round
(
within_1sd
100
,
1
)
,
"%"
)
)
The output of the code above is:
[1] "均值: 69.97"
[1] "标准差: 10.03"
[1] "±1 标准差范围内的比例: 68.1 %"
R Language Examples