在R中对非均匀分布列先归一化再进行分箱处理
Hey there! Let's work through your problem step by step—first normalizing that exponentially distributed Qty column, then binning it into 5 categories. Here's how to do it in R with your sample data:
Step 1: Normalize the Data
Since your data follows an exponential (highly skewed) distribution, a direct min-max normalization might cluster most values near 0. A better approach is to first apply a log transformation to reduce the impact of extreme values, then normalize. I'll show both options below:
Option 1: Log Transformation + Min-Max Normalization
This is ideal for skewed data like yours:
library(dplyr) # Load your sample data dat <- data.frame(Id = c(1,2,3,4,5,6,7,8), Qty = c(1,1,1,2,3,13,30,45)) # Add log-transformed and normalized columns dat <- dat %>% mutate( Log_Qty = log(Qty + 1), # +1 avoids log(0) errors Normalized_Qty = (Log_Qty - min(Log_Qty)) / (max(Log_Qty) - min(Log_Qty)) )
Option 2: Direct Min-Max Normalization (No Log)
If you prefer to use the raw data:
dat <- dat %>% mutate(Normalized_Qty = (Qty - min(Qty)) / (max(Qty) - min(Qty)))
Step 2: Bin the Normalized Data into 5 Categories
Choose one of these two common binning methods based on your needs:
Method 1: Equal-Quantile Binning (Balanced Sample Sizes)
Use dplyr::ntile() to split data into groups with roughly equal numbers of observations—perfect for non-uniform distributions:
dat <- dat %>% mutate(Binned_Category = ntile(Normalized_Qty, n = 5))
Method 2: Equal-Width Binning (Equal Range per Bin)
Use base::cut() to split the normalized data (range 0-1) into 5 equal-width intervals, then convert to integer category labels:
dat <- dat %>% mutate( Binned_Category = cut( Normalized_Qty, breaks = 5, labels = 1:5, include.lowest = TRUE ) %>% as.integer() )
Example Final Output
After running the log transformation + equal-quantile binning code, your data frame will look like this (matching your desired format):
> dat Id Qty Log_Qty Normalized_Qty Binned_Category 1 1 1 0.6931472 0.000000 1 2 2 1 0.6931472 0.000000 1 3 3 1 0.6931472 0.000000 1 4 4 2 1.0986123 0.142857 2 5 5 3 1.3862944 0.250000 3 6 6 13 2.6390573 0.714286 4 7 7 30 3.4339872 1.000000 5 8 8 45 3.8066625 1.142857 5
内容的提问来源于stack exchange,提问作者Rahul Agarwal

