Amateur
Amateur

Reputation: 1277

R error: number of items to replace is not a multiple of replacement length R

I wrote the following code and got the error: number of items to replace is not a multiple of replacement length at code line:

 X_after[count, ] = c(censN1, censN2, censN3)

After searching the internet, I found the problem is probably caused by the unmatched number of samples size of the pre-determine n_samples of NA and the final X_after dataset. How can I adjust the matrix code such that ncol is dynamically determined after the loop rather than pre-determined at n_samples? Or if you have other solutions to this error message, please chime in as well.

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)

Updates: After reading your comments, I made changes to these code lines and it is working. Thank you for your help.

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)

Upvotes: 1

Views: 14997

Answers (1)

mnel
mnel

Reputation: 115505

Your problem lies in the fact that sub_samples = n_samples/3 is not a whole number.

When you create a sample of fractional size it creates a sample of floor(size)

length(rlnorm(1.5,1,1)) 
## [1] 1

Thus, when you recombine your data length( c(censN1, censN2, censN3)) does not (necessarily) equal n_sample.

Thus, you need a method for dealing with numbers of samples that are not divisible by 3.

Upvotes: 6

Related Questions