你可以使用下面的基本语法来计算R中列的标准偏差。
#calculate standard deviation of one column
sd(df$col1)
#calculate standard deviation of all columns
sapply(df, sd)
#calculate standard deviation of specific columns
sapply(df[c('col1', 'col2', 'col5')], sd)
下面的例子展示了如何在以下数据框架中实际使用这种语法。
#create data frame
df <- data.frame(team=c('A', 'B', 'C', 'D', 'E'),
points=c(99, 91, 86, 88, 95),
assists=c(33, 28, 31, 39, 34),
rebounds=c(30, 28, 24, 24, 28))
#view data frame
df
team points assists rebounds
1 A 99 33 30
2 B 91 28 28
3 C 86 31 24
4 D 88 39 24
5 E 95 34 28
例1:一列的标准差
下面的代码显示了如何计算数据框中一列的标准差。
#calculate standard deviation of 'points' column
sd(df$points)
[1] 5.263079
points "列中数值的标准差是5.263079**。**
例2:所有列的标准差
下面的代码显示了如何计算数据框中每一列的标准差。
#calculate standard deviation of all columns in data frame
sapply(df, sd)
team points assists rebounds
NA 5.263079 4.062019 2.683282
Warning message:
In var(if (is.vector(x) || is.factor(x)) x else as.double(x), na.rm = na.rm) :
NAs introduced by coercion
由于'team'列是一个字符变量,R返回NA并给我们一个警告。
然而,它成功地计算了其他三个数字列的标准差。
例3:特定列的标准差
下面的代码显示了如何计算数据框架中特定列的标准差。
#calculate standard deviation of 'points' and 'rebounds' columns
sapply(df[c('points', 'rebounds')], sd)
points rebounds
5.263079 2.683282
注意,我们也可以使用列索引值来选择列。
#calculate standard deviation of 'points' and 'rebounds' columns
sapply(df[c(2, 4)], sd)
points rebounds
5.263079 2.683282
其他资源
下面的教程解释了如何在R中对列执行其他常见的功能。
如何在R中计算多列的平均值
如何在R中寻找跨多列的最大值
如何在R中选择特定列
The postHow to Calculate Standard Deviation of Columns in Rappeared first onStatology.