File: impPCA.R

package info (click to toggle)
r-cran-vim 6.2.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,556 kB
  • sloc: cpp: 141; sh: 12; makefile: 2
file content (302 lines) | stat: -rw-r--r-- 9,932 bytes parent folder | download
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#' Iterative EM PCA imputation
#'
#' Greedy algorithm for EM-PCA including robust methods
#'
#' @param x data.frame or matrix
#' @param method `"classical"` or `"mcd"` (robust estimation)
#' @param eps threshold for convergence
#' @param m number of multiple imputations (only if parameter `boot` equals `TRUE`)
#' @param k number of principal components for reconstruction of `x`
#' @param maxit maximum number of iterations
#' @param boot residual bootstrap (if `TRUE`)
#' @param verbose TRUE/FALSE if additional information about the imputation
#' process should be printed
#' @return the imputed data set. If `boot = FALSE` this is a data.frame. 
#' If `boot = TRUE` this is a list where each list element contains a data.frame. 
#' @author Matthias Templ
#' @references Serneels, Sven and Verdonck, Tim (2008). 
#' Principal component analysis for data containing outliers and missing elements. 
#' Computational Statistics and Data Analysis, Elsevier, vol. 52(3), pages 1712-1727
#' @keywords manip
#' @family imputation methods
#' @examples
#'
#' data(Animals, package = "MASS")
#' Animals$brain[19] <- Animals$brain[19] + 0.01
#' Animals <- log(Animals)
#' colnames(Animals) <- c("log(body)", "log(brain)")
#' Animals_na <- Animals
#' probs <- abs(Animals$`log(body)`^2)
#' probs <- rep(0.5, nrow(Animals))
#' probs[c(6,16,26)] <- 0
#' set.seed(1234)
#' Animals_na[sample(1:nrow(Animals), 10, prob = probs), "log(brain)"] <- NA
#' w <- is.na(Animals_na$`log(brain)`)
#' impPCA(Animals_na)
#' impPCA(Animals_na, method = "mcd")
#' impPCA(Animals_na, boot = TRUE, m = 10)
#' impPCA(Animals_na, method = "mcd", boot = TRUE)[[1]]
#' plot(`log(brain)` ~ `log(body)`, data = Animals, type = "n", ylab = "", xlab="")
#' mtext(text = "impPCA robust", side = 3)
#' points(Animals$`log(body)`[!w], Animals$`log(brain)`[!w])
#' points(Animals$`log(body)`[w], Animals$`log(brain)`[w], col = "grey", pch = 17)
#' imputed <- impPCA(Animals_na, method = "mcd", boot = TRUE)[[1]]
#' colnames(imputed) <- c("log(body)", "log(brain)")
#' points(imputed$`log(body)`[w], imputed$`log(brain)`[w], col = "red", pch = 20, cex = 1.4)
#' segments(x0 = Animals$`log(body)`[w], x1 = imputed$`log(body)`[w], y0 = Animals$`log(brain)`[w],
#' y1 = imputed$`log(brain)`[w], lty = 2, col = "grey")
#' legend("topleft", legend = c("non-missings", "set to missing", "imputed values"),
#' pch = c(1,17,20), col = c("black","grey","red"), cex = 0.7)
#' mape <- round(100* 1/sum(is.na(Animals_na$`log(brain)`)) * sum(abs((Animals$`log(brain)` -
#' imputed$`log(brain)`) / Animals$`log(brain)`)), 2)
#' s2 <- var(Animals$`log(brain)`)
#' nrmse <- round(sqrt(1/sum(is.na(Animals_na$`log(brain)`)) * sum(abs((Animals$`log(brain)` -
#' imputed$`log(brain)`) / s2))), 2)
#' text(x = 8, y = 1.5, labels = paste("MAPE =", mape))
#' text(x = 8, y = 0.5, labels = paste("NRMSE =", nrmse))
#'
#' @export
impPCA <- function(x, method = "classical", m = 1, eps = 0.5, 
                   k = ncol(x) - 1, maxit = 100, boot = FALSE,
                   verbose = TRUE){
  ### x ... Matrix or data.frame with missings
  ### method ... mcd, classical, gridMAD
  ### eps ... convergence criteria
  ### all.obs ... TRUE, if the whole observation should be replaced with the pca-estimate
  ###
  ### Matthias Templ
  ### original from 10.09.2006
  ### adapted 31.10.2006
  ### Imputation nach Sven
  ### Statistics Austria
  
  # classx <- class(x)
  classes <- lapply(x, class)
  if(!all(classes %in% c("numeric", "integer"))) stop("only numeric variables allowed")
  
  xorig <- x
  indexMiss <- is.na(x)
  
  #P <- dim(x)[2]
  
  ## erste Schaetzung mit Median:
  #w <- which(is.na(x), arr.ind=TRUE)
  # cm <- colMeans(x, na.rm=TRUE)  ## fuers Ruecktransf.
  # cmed <- apply(x, 2, median, na.rm = TRUE)
  # csd <- apply(x, 2, sd, na.rm = TRUE)   ## fuers Ruecktransf.
  # csdrob <- apply(x, 2, mad, na.rm = TRUE)   ## fuers Ruecktransf.  
  # xorig <- x
  # x <- apply(x, 2, function(x) (x - mean(x, na.rm=TRUE))/sd(x, na.rm=TRUE))

  ## centering and initialisierung
  # if(method == "classical"){
    cm <- colMeans(x, na.rm=TRUE)  ## fuers Ruecktransf.
    csd <- apply(x, 2, sd, na.rm = TRUE)   ## fuers Ruecktransf.
    x <- apply(x, 2, function(x) (x - mean(x, na.rm=TRUE))/sd(x, na.rm=TRUE))
    # initialise missing values
    for(j in 1:ncol(x)){
      x[indexMiss[,j], j] <- mean(x[, j], na.rm = TRUE) 
    }
  # } else if(method == "mcd"){
  #   cmed <- apply(x, 2, median, na.rm = TRUE)
  #   csdrob <- apply(x, 2, mad, na.rm = TRUE)   ## fuers Ruecktransf.
  #   x <- apply(x, 2, function(x) (x - median(na.omit(x))/mad(na.omit(x))))
  #   # initialise missing values
  #   for(j in 1:ncol(x)){
  #     x[indexMiss[,j], j] <- median(na.omit(x[, j]))
  #   }
  # }
  
  ### PCA, Iteration:
  d <- 1000000
  it <- 0
  
  if(!boot){

    while(d > eps & it <= maxit){
      it <- it + 1
      if( method == "mcd" ){ 
        xMcd <- robustbase::covMcd(x)
        p <- princomp(x, covmat=xMcd) 
      }
      if( method == "classical" ){ 
        p <- princomp(x) 
      }
      #if( method == "gridMAD" ){ p <- PCAgrid(x, method="mad", k=ncol(x)) }
      xneu <- p$sco[,1:k] %*% t(p$load[,1:k])  #(p$load[,1:P])   
      ##+rep(1,dim(x)[1])%*%t(xMcd$center)  # p-dim???
      d <- sum(abs(x[indexMiss] - xneu[indexMiss]))    ## Konvergenzkriterium
      x[indexMiss] <- xneu[indexMiss]
    }
    
    
    ### Ruecktrans:
    
    # if(method == "classical"){
      for( i in 1: dim(x)[2] ){
        x[,i] <- (x[,i] * csd[i]) + cm[i]
      }
    # } else {
    #   for( i in 1: dim(x)[2] ){
    #     x[,i] <- (x[,i] * csdrob[i]) + cmed[i]
    #   }
    # }
    if(verbose) message("\nIterations: ", it)
    return(data.frame(x))
  } else { # boot
    # create bootstrap samples
    
    if( method == "mcd" ){ 
      xMcd <- robustbase::covMcd(x)
      p <- princomp(x, covmat=xMcd) 
    }
    if( method == "classical" ){ 
      p <- princomp(x) 
    }
    
    xneu <- p$sco[,1:k] %*% t(p$load[,1:k]) 
    residuals <- x - xneu
    xboot <- x
    residualboot <- function(){
      for(j in 1:ncol(x)){
        xboot[, j] <- x[, j] + sample(residuals[,j], replace = TRUE)
      }
      
      ### PCA, Iteration:
      d <- 1000000
      it <- 0
      
      while(d > eps & it <= maxit){
        it <- it + 1
        if( method == "mcd" ){ 
          xMcd <- robustbase::covMcd(xboot)
          p <- princomp(xboot, covmat=xMcd) 
        }
        if( method == "classical" ){ 
          p <- princomp(xboot) 
        }
        #if( method == "gridMAD" ){ p <- PCAgrid(x, method="mad", k=ncol(x)) }
        xneu <- p$sco[,1:k] %*% t(p$load[,1:k])  
        d <- sum(abs(xboot[indexMiss] - xneu[indexMiss]))    ## Konvergenzkriterium
        xboot[indexMiss] <- xneu[indexMiss]
      }
      
      ### Ruecktrans:
      
      # if(method == "classical"){
        for( i in 1: dim(x)[2] ){
          xboot[,i] <- (xboot[,i] * csd[i]) + cm[i]
        }
      # } else {
      #   for( i in 1: dim(x)[2] ){
      #     xboot[,i] <- (xboot[,i] * csdrob[i]) + cmed[i]
      #   }        
      # }
      # 
      xorig[indexMiss] <- xboot[indexMiss]
      return(xorig)
    }
    
    res <- list()
    for(r in 1:m){
      res[[r]] <- residualboot()    
    }
    if(verbose) message("\nIterations: ", it)
    return(res)
  }
}

# impPCA_boot <- function(x, method = "classical", m = 10 , eps = 0.5, 
#                    k = ncol(x) - 1, maxit = 10){
#   ### x ... Matrix or data.frame with missings
#   ### method ... mcd, classical, gridMAD
#   ### eps ... convergence criteria
#   ### all.obs ... TRUE, if the whole observation should be replaced with the pca-estimate
#   ###
#   ### Matthias Templ
#   ### original from 10.09.2006
#   ### adapted 31.10.2006
#   ### Imputation nach Sven
#   ### Statistics Austria
#   
#   # classx <- class(x)
#   classes <- lapply(x, class)
#   if(!all(classes %in% c("numeric", "integer"))) stop("only numeric variables allowed")
#   
#   indexMiss <- is.na(x)
# 
#   #P <- dim(x)[2]
#   
#   ## erste Schaetzung mit Median:
#   #w <- which(is.na(x), arr.ind=TRUE)
#   cm <- colMeans(x, na.rm=TRUE)  ## fuers Ruecktransf.
#   cmed <- apply(x, 2, median, na.rm = TRUE)
#   csd <- apply(x, 2, sd, na.rm = TRUE)   ## fuers Ruecktransf.
#   xorig <- x
#   x <- apply(x, 2, function(x) (x - mean(x, na.rm=TRUE))/sd(x, na.rm=TRUE))
#   
#   ## Initialisierung
#   if(method == "classical"){
#     for(j in 1:ncol(x)){
#       x[indexMiss[,j], j] <- cm[j] 
#     }
#   } else if(method == "mcd"){
#     for(j in 1:ncol(x)){
#       x[indexMiss[,j], j] <- cmmed[j] 
#     }    
#   }
#   
#   # create bootstrap samples
#   
#   if( method == "mcd" ){ 
#     xMcd <- robustbase::covMcd(x)
#     p <- princomp(x, covmat=xMcd) 
#   }
#   if( method == "classical" ){ 
#     p <- princomp(x) 
#   }
#   
#   xneu <- p$sco[,1:k] %*% t(p$load[,1:k]) 
#   residuals <- x - xneu
#   xboot <- x
#   residualboot <- function(){
#     for(j in 1:ncol(x)){
#       xboot[, j] <- x[, j] + sample(residuals[,j], replace = TRUE)
#     }
#     
#     ### PCA, Iteration:
#     d <- 1000000
#     it <- 0
#     
#     while(d > eps & it <= maxit){
#       it <- it + 1
#       if( method == "mcd" ){ 
#         xMcd <- robustbase::covMcd(xboot)
#         p <- princomp(xboot, covmat=xMcd) 
#       }
#       if( method == "classical" ){ 
#         p <- princomp(xboot) 
#       }
#       #if( method == "gridMAD" ){ p <- PCAgrid(x, method="mad", k=ncol(x)) }
#       xneu <- p$sco[,1:k] %*% t(p$load[,1:k])  
#       d <- sum(abs(xboot[indexMiss] - xneu[indexMiss]))    ## Konvergenzkriterium
#       xboot[indexMiss] <- xneu[indexMiss]
#     }
#   
#     ### Ruecktrans:
#     
#     for( i in 1: dim(x)[2] ){
#       xboot[,i] <- (xboot[,i] * csd[i]) + cm[i]
#     }
#     xorig[indexMiss] <- xboot[indexMiss]
#     return(xorig)
#   }
#   
#   res <- list()
#   for(r in 1:m){
#     res[[r]] <- residualboot()    
#   }
# 
#   return(res)
# }
#