关于R语言base包.bincode()函数示例的结果困惑
.bincode() Behavior with Duplicate Breaks Let's break down why you're seeing that unexpected output—your confusion comes from assuming .bincode() automatically removes duplicate values in breaks, but that's not the case. Here's the step-by-step explanation:
1. How .bincode() Handles Your Input Breaks
Your breaks vector b <- c(0, 0, 1, 1) is non-decreasing, which meets .bincode()'s requirement for valid breaks. The function does not deduplicate or modify the breaks sequence in this scenario—it uses the exact sequence you provided.
With length(b) = 4, this creates length(b)-1 = 3 intervals. Since you set right = FALSE, each interval follows the left-closed, right-open format [breaks[i], breaks[i+1)).
2. The Generated Intervals
Here are the actual intervals created from your breaks:
- Interval 1:
[0, 0)→ An empty interval (no value can satisfy0 ≤ x < 0) - Interval 2:
[0, 1)→ All values where0 ≤ x < 1fall here - Interval 3:
[1, 1)→ Another empty interval
3. Matching Your x Values to Intervals
Now let's map each element in x <- c(0, 0.01, 0.5, 0.99, 1):
x=0: Doesn't fit Interval 1, but fits Interval 2 → returns code2x=0.01,x=0.5,x=0.99: All fall within Interval 2 → return code2x=1: Per.bincode()rules, whenright = FALSE, any value greater than or equal to the last break value (here,1) is considered outside the range of breaks → returnsNA
4. Getting Your Expected Output (If Needed)
If you want .bincode() to use deduplicated breaks, you'll need to clean the breaks manually first:
x <- c(0, 0.01, 0.5, 0.99, 1) b <- c(0, 0, 1, 1) clean_breaks <- sort(unique(b)) # Results in c(0, 1) # This will return [1, 1, 1, 1, NA] .bincode(x, clean_breaks, right = FALSE, include.lowest = FALSE)
To get x=1 to map to a valid code, you'd need to extend your breaks to include a value above 1 (e.g., clean_breaks <- c(0,1,2)), which would create a second interval [1,2) and return 2 for x=1.
内容的提问来源于stack exchange,提问作者Angus Zhang

