这是找出什么是的第一种方法object
:
na.impute <- function (object) {
browser()
print(object)
object
}
lda(my.dat[,-1], my.dat[,1], na.action=na.impute)
# Called from: na.action(structure(list(g = grouping, x = x), class = "data.frame"))
Browse[1]> str(object)
# 'data.frame': 0 obs. of 2 variables:
# $ g: num 0 1 0 1 1 0
# $ x: matrix [1:6, 1:2] 5 8 9 1 -1 NA -2.4 -4 -4.4 -0.5 ...
# ..- attr(*, "dimnames")=List of 2
# .. ..$ : NULL
# .. ..$ : chr "V2" "V3"
Browse[1]> object$g
# [1] 0 1 0 1 1 0
Browse[1]> object$x
# V2 V3
# [1,] 5 -2.4
# [2,] 8 -4.0
# [3,] 9 -4.4
# [4,] 1 -0.5
# [5,] -1 0.7
# [6,] NA -0.3
# attr(,"class")
# [1] "matrix"
所以它确实是一个不寻常的对象:structure(list(g = grouping, x = x), class = "data.frame")
。另一种看待这一点的方式,让我们检查函数lda
:
lda
# function (x, ...)
# UseMethod("lda")
# <bytecode: 0x0e3583fc>
# <environment: namespace:MASS>
methods(lda)
# [1] lda.collapsed.gibbs.sampler lda.data.frame* lda.default*
# [4] lda.formula* lda.matrix*
#
# Non-visible functions are asterisked
在这种情况下,我们对lda.data.frame
. 由于它带有星号,我们必须使用或者MASS:::lda.data.frame
查看getAnywhere("lda.data.frame")
源代码:
function (x, ...)
{
res <- lda(structure(data.matrix(x), class = "matrix"), ...)
cl <- match.call()
cl[[1L]] <- as.name("lda")
res$call <- cl
res
}
<bytecode: 0x067c3248>
<environment: namespace:MASS>
现在我们可以看到这lda.matrix
是需要的,所以再次使用两个函数之一:
function (x, grouping, ..., subset, na.action)
{
if (!missing(subset)) {
x <- x[subset, , drop = FALSE]
grouping <- grouping[subset]
}
if (!missing(na.action)) {
dfr <- na.action(structure(list(g = grouping, x = x),
class = "data.frame"))
grouping <- dfr$g
x <- dfr$x
}
res <- lda.default(x, grouping, ...)
cl <- match.call()
cl[[1L]] <- as.name("lda")
res$call <- cl
res
}
<bytecode: 0x067bf7b8>
<environment: namespace:MASS>
最后在这里我们找到了na.action
我们所期望的调用。现在这是一个NA
用列手段替换值的函数:
na.impute <- function (object) {
temp <- object$x
k <- which(is.na(temp), arr.ind = TRUE)
temp[k] <- colMeans(temp, na.rm = TRUE)[k[, 2]]
structure(list(g = object$g, x = as.matrix(temp)), class = "data.frame")
}
lda(my.dat[,-1], my.dat[,1], na.action=na.impute)
# Call:
# lda(my.dat[, -1], my.dat[, 1], na.action = na.impute)
#
# Prior probabilities of groups:
# 0 1
# 0.5 0.5
#
# Group means:
# V2 V3
# 0 6.133333 -2.366667
# 1 2.666667 -1.266667
#
# Coefficients of linear discriminants:
# LD1
# V2 -0.8155124
# V3 -1.1614265
现在考虑predict
它na.action
是不可用的选项:请参阅getAnywhere("predict.lda")
,没有使用此参数。