Juan Esteban de la Calle Juan Esteban de la Calle - 14 days ago 4x
R Question

Obtain the cut2 interval for numbers not previously included

Actually, I have solved this question, but I have problems because the solution is in two steps, which are really separated between each other (the first step is inside a function and the second step is inside another; this would imply me to make H as an output).

First, the replicable example:

RN = rnorm(n=1000,10,20)
H = cut2(RN,g=4,onlycuts=FALSE) # Step 1: The intervals are generated
H2= cut2(RN,g=4,onlycuts=TRUE) # Step 1: (This would be useful if Step 1 and 2 were not separated)
new_number = 10.53 # Step 2: New number
interval_new_number = cut2(new_number,cuts=H) # Step 2: Interval for new number

I would like to know a solution which can be done as:

new_number %in% H

Give me your opinion.

42- 42-

I (think) the request is for determination of the interval number for a new value relative to a factor vector constructed with cut2. If that is what is needed then use as.numeric on a gsub construction of the first of the two cuts in each factor level:

H = cut2(RN,g=4,onlycuts=FALSE)
[1] "factor"

[1] "[-66.7,-2.4)" "[ -2.4,10.3)" "[ 10.3,23.7)" "[ 23.7,75.9]"

findInterval( 10.53, as.numeric( gsub( "\\[|\\,.+$","", levels(H) ) ) )
[1] 3

I had never seen the onlycuts parameter used before but it would malke the code even easier since the as.numeric( gsub(...)) calls would not be needed:

> (H2 = cut2(RN,g=4,onlycuts=TRUE) )
[1] -66.687208  -2.397688  10.334926  23.659386  75.887076
> findInterval( 10.53, H2 )
[1] 3