我编写了以下代码并得到了错误:要替换的项目数不是代码行中替换长度的倍数:
X_after[count, ] = c(censN1, censN2, censN3)
在网上搜索后,我发现问题可能是由于预先确定n_samples
的NA
和最终 X_after
数据集的样本大小不匹配造成的。如何调整矩阵代码,使其ncol
在循环后动态确定,而不是在 n_samples 处预先确定?或者,如果您对此错误消息有其他解决方案,也请加入。
multiLodSim <- function (GM, GSD, 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)
mu <- log(GM)
sigma <- log(GSD)
lod1 <- quantile(rlnorm(100000,mu,sigma),p)
lod2 <- quantile(rlnorm(100000,mu,sigma),(p*0.95))
lod3 <- quantile(rlnorm(100000,mu,sigma),(p*0.9))
pct_cens <- numeric(n_iterations)
count <- 1
while(count <= n_iterations) {
sub_samples = n_samples/3 # divide the total sample into third (for 3 lods)
n1 <- rlnorm(sub_samples,mu,sigma)
censN1 <- sort(pmax(n1,lod1))
n2 <- rlnorm(sub_samples,mu,sigma)
censN2 <- sort(pmax(n2,lod1))
censN2[censN2==lod1] <- lod2
n3 <- rlnorm(sub_samples,mu,sigma)
censN3 <- sort(pmax(n3,lod1))
censN3 [censN3==lod1] <- lod3
X_after[count, ] = c(censN1, censN2, censN3)
delta [count, ] = X_after <= lod1 # nondetects= TRUE (1), detects= FALSE (0)
pct_cens [count] = mean(delta[count,]) #
if (pct_cens [count] > 0 & pct_cens [count] < 1 ) count <- count + 1}}
a = multiLodSim(GM=1,GSD=2,n_samples=20,n_iterations=5,p=0.3)
更新:阅读您的评论后,我对这些代码行进行了更改并且它正在工作。感谢您的帮助。
n1 = rlnorm(round(sub_samples),mu,sigma)
n2 = rlnorm(round(sub_samples),mu,sigma)
sub_samples3 = n_samples - length(n1)-length(n2)
n3 = rlnorm(subsamples3, mu,sigma)