1
我寫下面的代碼並得到了錯誤:項替換的數目不是在代碼行替換長度的倍數:半徑誤差:項替換的數目不更換長R的倍數
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)
凡樣本數的方法是'mu'和'sigma'的調用'rlnorm'定義? – mnel 2012-08-08 04:27:22
除了mnel的回答,我想你會在這一行遇到麻煩:'delta [count,] = X_after <= lod1'。如果你用'delta [count,] = X_after [count,] <= lod1'替換它(當然考慮到'X_after'和'delta'的ncol必須是一個倍數3) – Edward 2012-08-08 04:44:04
在最後的if語句/ while循環返回一些東西之後,你還需要在你的函數中有一行。 (我假設'X_after') – mnel 2012-08-08 04:45:39