Home > Software design >  R add to the for loop
R add to the for loop

Time:11-19

I have my code:

V_max=10
V_min=0
H=1
n=1
x_right <- 3.2
x1_right <- 11.8
par(mfrow=c(length(C) 1,1), mar = c(2,0,2,0),oma = c(1,5,0,0))


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)

mylist <- list()
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)
  y3 <- hist(x3, plot=FALSE,breaks=20)
  maans_to_hist <- unlist(mylist)
  plot(y3, col='gray48',xlim=c(x_lim_min,x_lim_max))
}

I want to improve my code so that it calculates for all iterations of my for loop the percentage of my observations in histograms that are

  1. less than x_right as one factor and
  2. less than x1_right but more than x_right as second factor

and recorded the results in 2 lists, one for each factor. Honestly, I have no idea how to do it, so I am asking experienced forum users for help

CodePudding user response:

Note that because R is vectorized you can usually avoid using explicit loops altogether. And you also do not need to define a function for V E.g.:

V_max=10
V_min=0
H=1
n=1
x_right <- 3.2
x1_right <- 11.8
par(mfrow=c(length(C) 1,1), mar = c(2,0,2,0),oma = c(1,5,0,0))

C=c(0,0.01,0.1,1)
len_C <- length(C)
x_lim_min=-1
x_lim_max=13

V <- 1 / (1   (C / H)^n) 
V_C <- V_max*V

x3 <- sapply(V_C, function(x) rnorm(100, x, 1))
means_x3 <- colMeans(x3)

y3 <- lapply(1:len_C, function(z) hist(x3[z], plot=FALSE,breaks=20))
# calculate checks using apply
check1 <- apply(x3, 2, function(x) sum(x < x1_right)) / 100
check2 <- apply(x3, 2, function(x) sum(x > x_right & x < x1_right)) / 100

If you check your Environment panel you will see that the scalars are expanded to vectors, a matrix (x3) and a list (y3). To plot the y3 elements, reference each by its list index number. E.g.:

plot(y3[[1]], col='gray48',xlim=c(x_lim_min,x_lim_max)))
  • Related