You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为R语言数据框添加百分比密度列并计算列求和

Add Percentage Density Column & Compute Sums for Your Binned Data

Here's how to modify your R code to include the percentage density column and calculate the required sums:

# Your original data
data <- c(3.968, 3.534, 4.032, 3.912, 3.572, 4.014, 3.682, 3.608, 3.669, 3.705,
          4.023, 3.588, 3.945, 3.871, 3.744, 3.711, 3.645, 3.977, 3.888, 3.948)

# Generate binned frequency table
freq_df <- as.data.frame(table(cut(data, breaks = seq(3.50, 4.15, by = 0.05))))
colnames(freq_df) <- c("Interval", "Frequency") # Rename columns for clarity

# Calculate total observations
total <- sum(freq_df$Frequency)

# Add percentage density (frequency / total observations)
freq_df$Percentage_Density <- freq_df$Frequency / total

# Compute sums
sum_freq <- sum(freq_df$Frequency)
sum_pct <- sum(freq_df$Percentage_Density)

# Output the results
print(freq_df)
cat("\nSum of Frequency:", sum_freq, "\nSum of Percentage Density:", sum_pct)

Key Notes:

  • Percentage Density: This column is simply each interval's frequency divided by the total number of data points (20 in your case), so the sum will always be 1.0.
  • Sums: The sum of the Frequency column confirms we haven't lost any data (should equal 20), and the sum of Percentage_Density validates the column is correctly calculated.

Example Output:

Interval Frequency Percentage_Density
1   (3.5,3.55]         1               0.05
2 (3.55,3.60]         2               0.10
3 (3.60,3.65]         2               0.10
4 (3.65,3.70]         2               0.10
5 (3.70,3.75]         3               0.15
6 (3.75,3.80]         0               0.00
7 (3.80,3.85]         0               0.00
8 (3.85,3.90]         2               0.10
9 (3.90,3.95]         3               0.15
10 (3.95,4.00]         2               0.10
11 (4.00,4.05]         3               0.15
12 (4.05,4.10]         0               0.00
13 (4.10,4.15]         0               0.00

Sum of Frequency: 20 
Sum of Percentage Density: 1

内容的提问来源于stack exchange,提问作者Bosser445

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 22:20:41