如何将Rdata数据集重新缩放至0-1范围并使累计频率和为1?
Hey there! Let's work through how to get your data scaled to the [0,1] range and ensure their cumulative sum ends at 1.
First, let's clear up why your current approach didn't hit the mark: The rescale() function from the scales package only does a linear transformation to map your data into the [0,1] interval. It doesn't adjust values to guarantee their total sum equals 1—its only job is to shift and stretch your data to fit the target range, not normalize their total.
Here are two straightforward solutions to meet your needs:
Solution 1: Rescale first, then normalize to sum to 1
This method keeps your data in the [0,1] range first, then adjusts each value so the total sum (and thus the final cumulative sum) equals 1.
library(scales) # Step 1: Rescale your data to the [0,1] interval t_rescaled <- rescale(df, to = c(0, 1)) # Step 2: Normalize the rescaled data so their total sum is 1 t_final <- t_rescaled / sum(t_rescaled) # Verify the final cumulative sum is 1 tail(cumsum(t_final), 1) # This should return 1
Since all values from rescale() sit between 0 and 1, dividing by their total sum will keep each value within [0,1] (the sum of positive values in this range is always greater than 0, so each value becomes a valid fraction of that total).
Solution 2: Directly normalize to sum to 1 (with optional range check)
If you don't strictly need the intermediate [0,1] step before locking in the sum of 1, you can skip the rescale and normalize your original data directly. This will make the total sum 1, and for most datasets with positive values (like yours), the normalized values will naturally stay within [0,1] (since the maximum value divided by the total sum will be ≤1).
# Directly normalize original data to sum to 1 t_final <- df / sum(df) # Optional: Check if all values are within [0,1] all(t_final >= 0 & t_final <= 1)
If for some edge case the normalized values exceed 1 (unlikely with your original positive data range), just fall back to Solution 1: rescale first, then normalize.
内容的提问来源于stack exchange,提问作者Asâra

