当您致电broom::tidy(fn) 时,您会收到一条错误消息:
错误:fitdist 类的对象没有整洁的方法
这是因为来自broom 的这个函数只有有限数量的“好用”的对象,完整列表请参见methods(tidy)。 (Read more 关于 R 中的 S3 方法。更多 here)。
因此,该函数不适用于 fitdist 对象,但适用于来自 MASS 的 fitdistr 对象(更“著名”)。
然后我们可以将class分配给fn,然后使用broom:
class(fn) <- ("fitdist", "fitdistr")
# notice that I've kept the original class and added the other
# you shouldn't overwrite classes. ie: don't to this: class(fn) <- "fitdistr"
broom::tidy(fn)
# # A tibble: 2 x 3
# term estimate std.error
# <chr> <dbl> <dbl>
# 1 mean 0.328 0.0192
# 2 sd 0.0791 0.0136
请注意,您只能看到parameters。如果您希望查看更多内容并将所有内容组织为“整洁”,您应该告诉我们更多关于您的预期输出的信息。
broom::tidy() 让你走到这一步,如果你想要更多,我会先定义我自己的方法函数,它适用于 class fitdist 对象,使用 reference tidy.fitdistr 方法,并调整它.
我将如何改编原始 broom::tidy() 代码的示例,对 fitdist 类使用 S3 方法。
定义自己的方法(类似于定义自己的函数):
# necessary libraries
library(dplyr)
library(broom)
# method definition:
tidy.fitdist <- function(x, ...) { # notice the use of .fitdist
# you decide what you want to keep from summary(fn)
# use fn$ecc... to see what you can harvest
e1 <- tibble(
term = names(x$estimate),
estimate = unname(x$estimate),
std.error = unname(x$sd)
)
e2 <- tibble(
term = c("loglik", "aic", "bic"),
value = c(unname(x$loglik), unname(x$aic), unname(x$bic))
)
e3 <- x$cor # I prefer this to: as_tibble(x$cor)
list(e1, e2, e3) # you can name each element for a nicer result
# example: list(params = e1, scores = e2, corrMatr = e3)
}
您现在可以这样称呼这个新的method:
tidy(fn) # to be more clear this is calling your tidy.fitdist(fn) under the hood.
# [[1]]
# # A tibble: 2 x 3
# term estimate std.error
# <chr> <dbl> <dbl>
# 1 mean 0.328 0.0192
# 2 sd 0.0791 0.0136
#
# [[2]]
# # A tibble: 3 x 2
# term value
# <chr> <dbl>
# 1 loglik 19.0
# 2 aic -34.0
# 3 bic -32.3
#
# [[3]]
# mean sd
# mean 1 0
# sd 0 1
注意class 是:
class(fn)
[1] "fitdist"
所以现在您实际上不需要像以前那样分配fitdistr(来自MASS)类。