"Running" Percentile for each row in a dataframe
I have a dataframe like the one below, which I have present only one row of it:
HSI.Close.org HSI.Close HSI.Close.1 HSI.Close.2 HSI.Close.3
1987-03-17 2629.3 2669.6 2721.2 2750.1 2760.9
HSI.Close.4 HSI.Close.5 HSI.Close.6 HSI.Close.7 HSI.Close.8
1987-03-17 2731.1 2820.4 2798.6 2798.4 2890.9
HSI.Close.9 HSI.Close.10 HSI.Close.11 HSI.Close.12
1987-03-17 2939.1 2894.3 2877.9 2843.6
HSI.Close.13 HSI.Close.14 HSI.Close.15 HSI.Close.16
1987-03-17 2873.6 2848.2 2879 2827.4
HSI.Close.17 HSI.Close.18 HSI.Close.19 HSI.Close.20
1987-03-17 2775.8 2801.5 2792.1 2766.1
HSI.Close.21 HSI.Close.22 HSI.Close.23 HSI.Close.24
1987-03-17 2740.5 2754.7 2739.5 2694.9
HSI.Close.25 HSI.Close.26 HSI.Close.27 HSI.Close.28
1987-03-17 2713.7 2673.6 2672.4 2636.6
HSI.Close.29 HSI.Close.30 HSI.Close.31 HSI.Close.32
1987-03-17 2606开发者_Python百科.4 2585.2 2553.3 2524
HSI.Close.33 HSI.Close.34 HSI.Close.35 HSI.Close.36
1987-03-17 2484.4 2499.4 2536.9 2533.9
HSI.Close.37 HSI.Close.38 HSI.Close.39 HSI.Close.40
1987-03-17 2449.9 2460.5 2542.6 2559.1
HSI.Close.41 HSI.Close.42 HSI.Close.43 HSI.Close.44
1987-03-17 2578.2 2590.8 2614.9 2561.7
HSI.Close.45 HSI.Close.46 HSI.Close.47 HSI.Close.48
1987-03-17 2603.3 2607.1 2583.9 2552.4
HSI.Close.49 HSI.Close.50 hi52 lo52
1987-03-17 2540.1 2568.3 2939.1 2449.9
Each row contains 52 data points, namely HSI.Close.org
, HSI.Close
and HSI.Close.1
to HSI.Close.50
.
I want to know which percentile does HSI.Close.org
present among the 52 data points in that particular row. I am thinking of using ddply
to as.numeric
the 52 data point, then use the quantile
command to check the 1-100 percentile, and to find the percentile by trial-and-error method. But I think this is kinda slow, any faster method is possible?
Thanks!
This is similar to Prasad's answer, but I've found the match
/ sort
combination to be slightly faster than ecdf
. Obviously, YMMV.
set.seed(21)
Data <- data.frame(t(runif(52)))
# Assuming value to be matched is in first column
percentile <- function(x) match(x[1], sort(x))/length(x)
apply(Data,1,percentile)
The easiest way is probably to use mapply
. Say df
is your data-frame. Then you can do:
df$Pctile <- mapply(function(row,x) ecdf(df[row,-1])(x), 1:nrow(df), df[,1])
Note: ecdf(z)
takes a vector z
of numbers and produces the "empirical cumulative distribution function" for z
, so when you do ecdf(z)(x)
you get the quantile where x
falls in this empirical distribution. And mapply(fn, a, b)
(in this case) takes a function fn
of two scalar args and produces a vector of results
[ fn( a[1], b[1] ), ..., fn( a[n], b[n] ) ]
精彩评论