這裏是如何找出什麼是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")
,有沒有這種說法的使用。
@阿倫,它來自MASS包。 – Brendon
有什麼我可以添加的? – Julius
@Julius,你的回答非常有幫助。謝謝。 – Brendon