Search code examples
rdataframeimputationr-mice

Getting and saving results from multiple data frames


I have nine different data frames df1, df2, df3, df4, df5, df6, df7, df8 and df9. I want to write a function that apply the following calculation using the mice package for each data frame individually:

imputed_Data <- mice(df, m=3, maxit = 3, method = 'pmm', seed = 500)

by the end, I should get nine different imputed_Data.

what I did is:

for(i in 9) {
  imputed_Data <- mice(df[[i]], m=3, maxit = 3, method = 'pmm', seed = 500)
  result[[i]] <- mice::complete(imputed_Data)
  }

Solution

  • Put your df's in a list

    library(purrr)
    dfList <- list(df1, df2, df3, df4, df5, df6, df7, df8,  df9)
    

    This will give it to you as a list of df's.

    ## NOT RUN ##
    imputed_data <- 
      map(dfList, ~ mice(.x, m=3, maxit = 3, method = 'pmm', seed = 500)) 
    

    If you want it as a single concatenated df

    imputed_data <- 
      map_df(dfList, ~ mice(.x, m=3, maxit = 3, method = 'pmm', seed = 500))