如何在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: Usedsum(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 conditionx3 > x_right & x3 < x1_rightto count valid entries, then computed the proportion relative to total observations.
- For values less than
- 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
Cvalue 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
相关产品推荐
相关产品推荐

