开始学习
< 返回

R 语言 – 均值和中值

在统计学中,我们通常对三个值感兴趣:

英文 中文 说明
Mean 均值 算术平均值
Median 中值 中位数
Mode 众数 一组数据中出现次数最多的那个数

均值(Mean)

假设我们要从 mtcars 数据集中计算变量的平均值,那么需要找到所有值的总和,并将总和除以值的数量。

观察 wt (weight) 值的排序:

1.513 1.615 1.835 1.935 2.140 2.200 2.320 2.465
2.620 2.770 2.780 2.875 3.150 3.170 3.190 3.215
3.435 3.440 3.440 3.440 3.460 3.520 3.570 3.570
3.730 3.780 3.840 3.845 4.070 5.250 5.345 5.424

使用 mean() 函数计算车辆重量(wt)的平均值:

Data_Cars <- mtcars

mean(Data_Cars$wt)

结果为:

[1] 3.21725

中值(Median)

中值是在对所有值进行排序后位于中间的值。如果数据数量为奇数,则中值为中间的那个数;如果数据数量为偶数,则中值为中间的那两个数值的平均值。

下面我们看一下 wt 变量的值(来自 mtcars 数据集),我们可以比较容易找到中间有两个数字。

观察 wt (weight) 值的排序:

1.513 1.615 1.835 1.935 2.140 2.200 2.320 2.465
2.620 2.770 2.780 2.875 3.150 3.170 3.190 3.215
3.435 3.440 3.440 3.440 3.460 3.520 3.570 3.570
3.730 3.780 3.840 3.845 4.070 5.250 5.345 5.424

注意:如果中间有两个数字,则必须将这些数字的总和除以二,才能找到中位数。

幸运的是,R 有一个函数可以为你完成所有这些工作 —— 只需使用 median() 函数即可找到中间值。

Note: If there are two numbers in the middle, you must divide the sum of those numbers by two, to find the median.

Luckily, R has a function that does all of that for you: Just use the median() function to find the middle value:

示例:计算车辆重量(wt)的中间值

Data_Cars <- mtcars

median(Data_Cars$wt)

结果为:

[1] 3.325

众数(Mode)

众数是出现次数最多的值。

R 没有计算众数的函数。但是,我们可以创建自己的函数来查找它。

如果我们看一下 wt 变量的值(来自 mtcars 数据集),我们会看到数字 3.440 经常出现。

观察 wt (weight) 值的排序:

1.513 1.615 1.835 1.935 2.140 2.200 2.320 2.465
2.620 2.770 2.780 2.875 3.150 3.170 3.190 3.215
3.435 3.440 3.440 3.440 3.460 3.520 3.570 3.570
3.730 3.780 3.840 3.845 4.070 5.250 5.345 5.424

我们不用自己去数,可以用下面的代码来找出众数。

Data_Cars <- mtcars

names(sort(-table(Data_Cars$wt)))[1]

结果为:

[1] "3.44"

从上面的例子中,我们现在知道在 mtcars 数据集中 wt 变量出现次数最多的数字是 3.443.440 lbs

Was this article helpful?
0 out of 5 stars
5 Stars 0%
4 Stars 0%
3 Stars 0%
2 Stars 0%
1 Stars 0%
Please Share Your Feedback
How Can We Improve This Article?
文章目录