r - Create a factor variable using the quantiles -


i'd create factor variable using quantiles of other variable a.

i tried code :

> cut(value, breaks=quantile(value, probs=seq(0,1, by=0.25)),       include.lowest=true)) 

but doesn't work because of quantiles same, doesn't know how cut.

>  'breaks' not unique 

example : q1=2 q2=5 q3=5 q4=8

how can in case ? maybe can cut randomly in case

this seems work

x=c(2,5,5,8,10) qnt <- quantile(x,seq(0,1,.25))  cut(x,unique(qnt),include.lowest=true) # [1] [2,5]  [2,5]  [2,5]  (5,8]  (8,10] # levels: [2,5] (5,8] (8,10] 

alternative answer. if still want 4 bins, when data not justify it, there way!

set.seed(1024) x <- sample(1:3,101,replace=true)  binx <- rank(x,ties.method="random")%/%(ceiling(length(x)/4)+1) 

and here can see effects.

binx_ranges <- by(x,binx,range) # binx: 0 # [1] 1 1 # ------------------------------------------------------------  # binx: 1 # [1] 1 2 # ------------------------------------------------------------  # binx: 2 # [1] 2 3 # ------------------------------------------------------------  # binx: 3 # [1] 3 3  table(binx,x) #     x # binx  1  2  3 #    0 26  0  0 #    1  8 19  0 #    2  0 13 14 #    3  0  0 21 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -