Amateur
Amateur

Reputation: 1277

use apply function to 2 separate lists in R

I have the following code to create a sample function and to generate simulated data

mean_detects<- function(obs,cens) {
 detects <- obs[cens==0]
 nondetects <- obs[cens==1]
 res <- mean(detects)
 return(res) 
}

mu <-log(1); sigma<- log(3); n_samples=10, n_iterations = 5; p=0.10
dset2 <- function (mu, sigma, n_samples, n_iterations, p) {
  X_after <- matrix(NA_real_, nrow = n_iterations, ncol = n_samples)
  delta <- matrix(NA_real_, nrow = n_iterations, ncol = n_samples)
  lod <- quantile(rlnorm(100000, mu, sigma), p = p)
  pct_cens <- numeric(n_iterations)
  count <- 1
  while(count <= n_iterations) {     
  X_before <- rlnorm(n_samples, mu, sigma)
  X_after[count, ] <- pmax(X_before, lod)
  delta [count, ] <- X_before <= lod
  pct_cens[count] <- mean(delta[count,])
  if (pct_cens [count]  > 0 & pct_cens [count] < 1 ) count <- count + 1 }
  ave_detects <- mean_detects(X_after,delta)  ## how can I use apply or other functions here?
  return(ave_detects) 

}

If I specify n_iterations, I will have a 1x10 X_after matrix and also 1x10 delta matrix. Then the mean_detects function works fine using this command.

ave_detects <- mean_detects(X_after,delta) 

however when I increase n_iterations to say 5, then I will have 2 5x10 X_after and delta then the mean_detects function does not work any more. It only gives me output for 1 iteration instead of 5. My real simulation has thousands of iterations so speed and memory must also be taken into account.

Edits: I edited my code based your comments. The mean_detects function that I created was meant to show an example the use of X_after and delta matrices simultaneously. The real function is very long. That's why I did not post it here.

Upvotes: 0

Views: 108

Answers (1)

csgillespie
csgillespie

Reputation: 60462

Your actual question isn't really clear. So,

  1. "My function only takes in 1 dataframe".
    • Actually your function takes in two vectors
  2. Write code that can use both X_after and delta. This doesn't really mean anything - sorry.
  3. "speed and memory must be taken into account". This is vague. Will your run out of memory? As a suggestion, you could think about a rolling mean. For example,

    x = runif(5)
    total = 0
    for(i in seq_along(x)) {
       total = (i-1)*total/i + x[i]/i
      cat(i, ": mean ", total, "\n")
    }
    1 : mean  0.4409 
    2 : mean  0.5139 
    3 : mean  0.5596 
    4 : mean  0.6212 
    5 : mean  0.6606 
    

Aside

  1. Your dest2 function requires the variable n (which you haven't defined).
  2. Your dest2 function doesn't return an obvious value.
  3. your mean_detects function can be simplified to:

    mean(obs[cens==0])
    

Upvotes: 2

Related Questions