我正在尋找一種方法來獲取有序向量并回傳每個值第一次出現的通過向量的百分比。
有關輸入向量和預期結果,請參見下文。
InputVector<-c(1,1,1,1,1,2,2,2,3,3)
ExpectedResult<-data.frame(Value=c(1,2,3), Percentile=c(0,0.5,0.8))
在這種情況下,1 出現在第 0 個百分位數,2 出現在第 50 個百分位數,3 出現在第 80 個百分位數。
uj5u.com熱心網友回復:
在基礎 R 中,使用rle和cumsum:
p <- with(rle(InputVector), cumsum(lengths) / sum(lengths))
c(0, p[-length(p)])
#[1] 0.0 0.5 0.8
uj5u.com熱心網友回復:
使用rank()和unique():
data.frame(
Value = InputVector,
Percentile = (rank(InputVector, ties.method = "min") - 1) / length(InputVector)
) |>
unique()
#> Value Percentile
#> 1 1 0.0
#> 6 2 0.5
#> 9 4 0.8
您也可以使用dplyr::percent_rank(),但請注意它以不同方式計算百分位數:
library(dplyr)
tibble(
Value = InputVector,
Percentile = percent_rank(Value)
) %>%
distinct()
#> # A tibble: 3 × 2
#> Value Percentile
#> <dbl> <dbl>
#> 1 1 0
#> 2 2 0.556
#> 3 4 0.889
使用reprex v2.0.2創建于 2022-11-09
uj5u.com熱心網友回復:
用于match_base R
(match(unique(InputVector), InputVector)-1)/length(InputVector)
[1] 0.0 0.5 0.8
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/530807.html
標籤:r
