r - 获取对应于每个四分位数的观测值

标签 r dataframe quantile

q <- quantile(faithful$eruptions)
> q
     0%     25%     50%     75%    100% 
1.60000 2.16275 4.00000 4.45425 5.10000 

我得到以下结果,数据集在 R 中提供。
 head(faithful)
  eruptions waiting
1     3.600      79
2     1.800      54
3     3.333      74
4     2.283      62
5     4.533      85
6     2.883      55

我想要一个包含数据的数据框和一个额外的列,用于指出每个观察值所属的分位数。例如,最终的数据集应该看起来像
     eruptions waiting Quartile
1     3.600      79      Q1
2     1.800      54      Q2
3     3.333      74
4     2.283      62
5     4.533      85
6     2.883      55

如何才能做到这一点?

最佳答案

类似的东西?使用来自 quantile 的值用作切割所需向量的值。

faithful$kva <- cut(faithful$eruptions, q)
levels(faithful$kva) <- c("Q1", "Q2", "Q3", "Q4")
faithful

    eruptions waiting  kva
1       3.600      79   Q2
2       1.800      54   Q1
3       3.333      74   Q2
4       2.283      62   Q2
5       4.533      85   Q4

关于r - 获取对应于每个四分位数的观测值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22009940/

相关文章:

R S3 类 : Decide between overwriting vs appending the class name of the class attribute

python - 多个数据帧上的 Pandas 元素条件操作

excel - 如何在 Pandas 数据框列中插入逗号作为千位分隔符?

python - 盘中数据的每日高/低

r - 左对齐两个图形边缘(ggplot)

r - 如何读取csv数据

r - 多个 Wilcox 测试作为 R 中的循环

python - 使用 xarray 滚动分位数

python - 将分位数作为多列添加到数据框中

R : know table(s), 如何计算四分位数)