你打电话时broom::tidy(fn)
您收到一条错误消息:
错误:fitdist 类的对象没有整洁的方法
这是因为这个函数来自broom
只有有限数量的“好用”的对象,请参阅methods(tidy)
获取完整列表。 (阅读更多 http://adv-r.had.co.nz/S3.html关于 R 中的 S3 方法。 更多here https://adv-r.hadley.nz/s3.html).
所以该函数不适用于对象fitdist
但适用于fitdistr
对象来自MASS
(更有名”)。
然后我们可以分配给fn
that class
,然后使用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
对象使用 as参考 https://github.com/tidymodels/broom/blob/master/R/mass-fitdistr-tidiers.R the tidy.fitdistr
方法,并对其进行调整。
我如何改编原作的示例broom::tidy()
代码,使用类的 S3 方法fitdist
.
定义你自己的方法(类似于定义你自己的函数):
# 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
now:
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
is:
class(fn)
[1] "fitdist"
所以现在你实际上不需要分配fitdistr
(from MASS
)像以前一样上课。