2

Here is just example data:

# generation of correlated data   
matrixCR <- matrix(NA, nrow = 100, ncol = 100)
diag(matrixCR) <- 1
matrixCR[upper.tri (matrixCR, diag = FALSE)] <- 0.5
matrixCR[lower.tri (matrixCR, diag = FALSE)] <- 0.5
matrixCR[1:10,1:10]
L = chol(matrixCR)# Cholesky decomposition
nvars = dim(L)[1]
nobs = 200
set.seed(123)
rM = t(L) %*% matrix(rnorm(nvars*nobs), nrow=nvars, ncol=nobs)
rM1 <- t(rM)
rownames(rM1) <- paste("S", 1:200, sep = "") 
colnames(rM1) <- paste("M", 1:100, sep = "")
# introducing missing value to the dataset 
N <- 2000*0.05 # 5% random missing values 
inds <- round ( runif(N, 1, length(rM1)) )
rM1[inds] <- NA


# using random forest implemented in mice package 
require(mice)
out.imp <- mice(rM1, m = 5, method ="rf")
imp.data <- complete(out.imp)

I am getting following error:

 iter imp variable
  1   1  M1  M2Error in apply(forest, MARGIN = 1, FUN = function(s) sample(unlist(s),  : 
  dim(X) must have a positive length

I am not sure what is causing this problem ?

1
  • 2
    The mice function seems to be throwing an error whenever it gets to a column with only a single missing value. I figured this out by running your code and successively excluding the columns where it failed. Then I compared the failing and succeeding columns and the only difference was that the failing columns had only one NA value. When I recreated your matrix, but with a 50% chance of a missing value (so no column would have only one NA) the code ran fine. I don't know if this is a bug or if there's some reason why having only one NA in a column should cause an error.
    – eipi10
    May 31, 2014 at 22:53

1 Answer 1

2

As I mentioned in my comment, when the method is set to randomforest (rf), the mice function is throwing an error whenever it gets to a column with only a single NAvalue, but runs fine with any other number of NA values.

I checked with the package author and this appears to be a bug. Until it's fixed, you can choose a different imputation method for those columns with a single NA value. For example:

# Count number of NA in each column
NAcount = apply(rM1, 2, function(x) sum(is.na(x)))

# Create a vector giving the imputation method to use for each column. 
# Set it to "rf" unless that column has exactly one NA value.
method = rep("rf", ncol(rM1))
method[which(NAcount==1)] = "norm"

# Run the imputation with the new "method" selections
out.imp <- mice(rM1, m = 5, method = method)

I realize that for consistency you may want to use the same imputation method for all the columns, but the above gives you an option if you're set on using the randomforest method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.