百分位数是一种统计度量,表示低于该值的百分比数据。
例如,**第 70** 个百分位数是 **70%** 的观测值可能低于的值。
在 R 中计算百分位数
在 R 中,我们使用 quantile()
函数来计算百分位数。例如,
marks <- c(97, 78, 57, 64, 87)
# calculate 70th percentile of marks
result <- quantile(marks, 0.70)
print(result)
输出
70% 85.2
在上面的示例中,我们使用 quantile()
函数计算了 marks 向量的**第 70** 个百分位数。请注意代码,
quantile(marks, 0.70)
这里,
- marks - 要计算百分位数的向量
- **0.70** - 百分位数的值。对于**第 70** 个百分位数,我们使用 **0.70** 参数
在 R 中计算向量的多个百分位数
我们使用 c()
函数一次性将多个百分位数传递给 R 中的 quantile()
。例如,
marks <- c(97, 78, 57, 64, 87)
# calculate 70th, 50th, 80th percentile of marks
result <- quantile(marks, c(0.7, 0.5, 0.8))
print(result)
输出
70% 50% 80% 85.2 78.0 89.0
在这里,我们使用 c()
函数一次性传递了多个百分位数:**0.7、0.5、0.8** 给 quantile()
。
因此,quantile()
分别返回 marks 的**第 70**、**第 50** 和**第 80** 个百分位数。
在 R 数据框中计算百分位数
R 允许我们计算特定_数据框_列的百分位数。例如,
# Create a data frame
dataframe1 <- data.frame (
Name = c("Juan", "Kay", "Jay", "Ray", "Aley"),
Age = c(22, 15, 19, 30, 23),
ID = c(101, 102, 103, 104, 105)
)
# calculate 55th and 27th percentile of the Age column
result <- quantile(dataframe1$Age, c(0.55, 0.27))
print(result)
输出
55% 27% 22.20 19.24
在这里,我们计算了 dataframe1 数据框的 Age 列的**第 55** 和**第 27** 个百分位数。