[英]use apply function to 2 separate lists in R
我有以下代码来创建一个示例函数并生成模拟数据
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)
}
如果我指定n_iterations,我将有一个1x10 X_after矩阵和1x10 delta矩阵。 然后使用此命令可以正常运行mean_detects函数。
ave_detects <- mean_detects(X_after,delta)
然而,当我将n_iterations增加到5时,那么我将有2个5x10 X_after和delta然后mean_detects函数不再起作用。 它只给出了1次迭代而不是5次的输出。我的真实模拟有数千次迭代,因此还必须考虑速度和内存。
编辑:我根据您的评论编辑了我的代码。 我创建的mean_detects函数旨在显示同时使用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_detects
函数可以简化为:
mean(obs[cens==0])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.