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

如何在R语言for循环中计算直方图观测值区间占比并存储结果?

Modified R Code
V_max=10
V_min=0
H=1
n=1
x_right <- 3.2
x1_right <- 11.8

V <- function( C, H, n ){
  1 / (1 + (C / H)^n) 
}

x_lim_min=-1
x_lim_max=13

C=c(0,0.01,0.1,1)

# Initialize empty lists to store the two types of proportions
prop_less_xright <- list()
prop_between_xright_x1right <- list()
mylist <- list() # Keep original list for storing means

# Set plot layout after defining C to ensure correct row count
par(mfrow=c(length(C),1), mar = c(2,0,2,0), oma = c(1,5,0,0))

for(i in 1:length(C)){
  V_C <- V_max*V(C[i],H,n)
  x3 <- rnorm(100,V_C,1)
  mylist[[i]] <- mean(x3)
  
  # Calculate proportion of observations less than x_right
  p_less <- sum(x3 < x_right) / length(x3)
  # Calculate proportion of observations between x_right and x1_right
  p_between <- sum(x3 > x_right & x3 < x1_right) / length(x3)
  
  # Store results in respective lists
  prop_less_xright[[i]] <- p_less
  prop_between_xright_x1right[[i]] <- p_between
  
  # Generate and plot histogram
  y3 <- hist(x3, plot=FALSE, breaks=20)
  plot(y3, col='gray48', xlim=c(x_lim_min,x_lim_max), main=paste("C =", C[i]))
}

# Optional: Convert lists to vectors for easier analysis
prop_less_vec <- unlist(prop_less_xright)
prop_between_vec <- unlist(prop_between_xright_x1right)

# Print results to console
cat("Proportions less than x_right:\n")
print(prop_less_vec)
cat("\nProportions between x_right and x1_right:\n")
print(prop_between_vec)

Key Changes Explained

  • List Initialization: Created two empty lists before the loop to store the two types of proportions separately.
  • Proportion Calculation:
    • For values less than x_right: Used sum(x3 < x_right) to count qualifying observations, then divided by total observations to get the proportion.
    • For values in the range (x_right, x1_right): Used a combined logical condition x3 > x_right & x3 < x1_right to count valid entries, then computed the proportion relative to total observations.
  • List Storage: Used double brackets ([[i]]) to store each proportion as a scalar in the lists, avoiding nested list structures.
  • Plot Improvements: Added a title to each histogram showing the current C value for clarity, and adjusted the plot layout to match the exact number of histograms needed.
  • Optional Vector Conversion: Included unlist() to convert the result lists to vectors, which are easier to use for further calculations or visualization.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:01:02