简体   繁体   中英

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.

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)
attributes(H)
#----
$class
[1] "factor"

$levels
[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 make 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM