Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/134.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
对R中的两个单独列表使用apply函数_R_Apply - Fatal编程技术网

对R中的两个单独列表使用apply函数

对R中的两个单独列表使用apply函数,r,apply,R,Apply,我有以下代码来创建示例函数并生成模拟数据 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 <- fun

我有以下代码来创建示例函数并生成模拟数据

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) 

}

mean\u你的实际问题并不十分清楚。所以

  • “我的函数只接受1个数据帧”。
    • 实际上你的函数有两个向量
  • 编写可以同时使用X_after和delta的代码。这并不意味着什么-对不起
  • “必须考虑速度和内存”。这是模糊的。你的内存会用完吗?作为建议,您可以考虑滚动平均值。比如说,

    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 
    
  • 旁白

  • dest2
    函数需要变量
    n
    (尚未定义)
  • dest2
    函数没有返回明显的值
  • 您的
    均值检测功能可以简化为:

    mean(obs[cens==0])
    
  • mean(obs[cens==0])