-
Notifications
You must be signed in to change notification settings - Fork 45
/
merge.mids.R
executable file
·39 lines (35 loc) · 1.29 KB
/
merge.mids.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#' Merge imputed dataset with original data.frame.
#'
#' Returns a data.frame where the variables in the original (i.e. \code{y}
#' parameter) are replaced by the imputed variables from mice (i.e. \code{x}
#' parameter).
#'
#' @param x the results from [mice::mice()].
#' @param y the `data.frame` passed to [mice::mice()]. This must
#' have the same number rows, but may contain additional columns.
#' @param shadow.matrix if TRUE, addtional columns will be added indicating
#' whether the value was missing in the original data.frame.
#' @param shadow.suffix the suffix used for the shadow matrix.
#' @param ... parameters passed to [mice::complete()].
#' @export
#' @method merge mids
#' @importFrom mice complete mice
merge.mids <- function(x, y,
shadow.matrix = FALSE,
shadow.suffix = '_missing',
...) {
df.mice <- mice::complete(x, ...)
if(!is.data.frame(y)) {
stop('The y parameter must be a data.frame.')
}
if(nrow(df.mice) != nrow(y)) {
stop('Number of rows in data.frame and imputed dataset do not match.')
}
df <- cbind(y[,!names(y) %in% names(df.mice)], df.mice)
if(shadow.matrix) {
shadow <- as.data.frame(is.na(y[,names(y) %in% names(df.mice)]))
names(shadow) <- paste0(names(shadow), shadow.suffix)
df <- cbind(df, shadow)
}
return(df)
}