amices / mice

Multivariate Imputation by Chained Equations
https://amices.org/mice/
GNU General Public License v2.0
445 stars 108 forks source link

Error in is.data.frame(x) : (list) object cannot be coerced to type 'double' #208

Closed stefvanbuuren closed 4 years ago

stefvanbuuren commented 4 years ago

The following example was kindly contributed by Leonhard Bakker. It shows that mice 3.6.0 does not work with nested data frames, for example, as created by tibble::add_column().

Error description

When using the mice() function, the error

Error in is.data.frame(x) : (list) object cannot be coerced to type 'double'

was returned. The error originated from a coding error. A function returned a variable as a data.frame, which was added to the dataset using the tibble::add_column() function. The dataset now comprised a variable with the class data.frame, which resulted in the error message.

Generate the data

This error was replicated using the mice::nhanes2 dataset. The chl variable is dropped first from the test dataset and subsequently the chl variable is added as a data.frame using the tibble::add_column() function.

library(mice)
library(tidyverse)

nhanesTest <- mice::nhanes2

testVar <- as.data.frame(
      mice::nhanes2 %>%
        select(chl)
    )

nhanesTest <- nhanesTest %>%
  select(-chl) %>%
  add_column(testVar)

str(nhanesTest)

Replicate the error

mice(
  nhanesTest
)
stefvanbuuren commented 4 years ago

To do: mice should detect this case, and generate a proper error.

stefvanbuuren commented 4 years ago

After commit ee3ac80 we now have

mice(nhanesTest)
Error in check.dataform(data) : 
  Cannot handle columns with class data.frame: testVar

For now this solves the cryptic error message.

For the future, it would be interesting to extend mice to handle this case, for example, using the blocks feature.