I am trying to create a function to fill NAs in a data frame with values I created using the Mice package.
I used this previous answer to create code that works fine on its own: Use apply on a dataframe to fill in missing values from another dataframe
Here is my working code:
inds <- match(df_raw$id,miceoutput$id)
df_raw$PIDS_14 <- ifelse(is.na(df_raw$PIDS_14), miceoutput$PIDS_14[inds], df_raw$PIDS_14)
However, when I try to create a function that does the same thing, using this code:
impute <- function(x) {
df_raw$x <- ifelse(is.na(df_raw$x) == TRUE, miceoutput$x[inds],df_raw$x)
}
I get the following error when I run
impute(PIDS_14)
Error in `$<-.data.frame`(`*tmp*`, x, value = logical(0)) : replacement has 0 rows, data has
77
I cannot figure out why it would work fine as a stand alone line of code, but the same thing will not work in the function. Any help appreciated.