我怎样让glht函数打印使用的自由度?

huangapple go评论71阅读模式
英文:

How can I make the glht function print the degrees of freedom used?

问题

Sorry, I can't fulfill your request to provide translations for code. If you have any other non-code-related text that needs translation, feel free to ask.

英文:

My question is a bit more general, and was already asked here enter link description here. However, there seems to be no general solution. Therefore, I try to use an example. What is an efficient way to proceed to get the summary function applied to a glht object print the degrees of freedom used by the glht to compute the p-values? I think I should add an argument to the summary function, but which one?

答案1

得分: 2

?glht的“Value”部分中提到,dfglht输出的一个组成部分,因此如果g是一个glht对象,即glht的输出,那么以下内容显示了摘要和自由度。您可以只执行这两行或者将其包装在一个函数中,如果您喜欢的话。

summary(g)
g$df

这也有效,因为summary.glht维护了df组件:

s <- summary(g)
s
s$df
英文:

In the Value section of ?glht it says that df is a component of the output of glht so if g is a glht object, i.e. the output of glht, then the following shows the summary and the degrees of freedom. You can just issue the two lines or wrap it in a function if you like.

summary(g)
g$df

This also works since summary.glht maintains the df component:

s &lt;- summary(g)
s
s$df

答案2

得分: 1

以下是您要翻译的内容:

"The most reliable way to find the possible arguments is to look into the function code. The summary function returns a list object, what governs what's printed is the print() function, so that's what we want to analyze.

But print() is a generic function, this is an Object Oriented Programming that basically means 'a function that has different methods for each type of object it can receive'. Running the code print gets us:

function (x, ...) 
UseMethod("print")

So we can't access the specific method of print() that it's used with a glht summary. To do that, we can either use debugging, or use the sloop package:

sloop::s3_methods_generic('print')

# A tibble: 403 × 4
   generic class       visible source             
   <chr>   <chr>       <lgl>   <chr>              
 1 print   aareg       FALSE   registered S3method
 2 print   abbrev      FALSE   registered S3method
 3 print   acf         FALSE   registered S3method
 4 print   all_vars    FALSE   registered S3method
 5 print   anova       FALSE   registered S3method
 6 print   Anova       FALSE   registered S3method
 7 print   anova.loglm FALSE   registered S3method
 8 print   any_vars    FALSE   registered S3method
 9 print   aov         FALSE   registered S3method
10 print   aovlist     FALSE   registered S3method
# ℹ 393 more rows

这些都是您为 print() 安装的方法。现在选择与 glht 相关的方法:

sloop::s3_methods_generic('print') |> filter(grepl('glht', class))

# A tibble: 3 × 4
  generic class        visible source             
  <chr>   <chr>        <lgl>   <chr>              
1 print   confint.glht FALSE   registered S3method
2 print   glht         FALSE   registered S3method
3 print   summary.glht FALSE   registered S3method

因此,我们想要 print.summary.glht() 方法的代码(这是方法的默认语法,function.class):

sloop::s3_get_method('print.summary.glht')

function (x, digits = max(3, getOption("digits") - 3), ...) 
{
    cat("\n\t", "Simultaneous Tests for General Linear Hypotheses\n\n")
    if (!is.null(x$type))
... #I omitted the rest of the function

现在我们可以看到参数是 xdigits(全局定义的),和 ...(在方法中没有使用)。因此,总之,没有一个参数可以显示自由度。

但是,既然您可以访问函数的代码,您可以自己修改它,在末尾添加 cat("Degrees of Freedom: ", x$df, "\n"),并以相同的名称保存它:

print.summary.glht <- function (x, digits = max(3, getOption("digits") - 3), ...){
  cat("\n\t", "Simultaneous Tests for General Linear Hypotheses\n\n")
  if (!is.null(x$type)) 
    cat("Multiple Comparisons of Means:", x$type, "Contrasts\n\n\n")
  call <- if (isS4(x$model)) 
    x$model@call
  else x$model$call
  if (!is.null(call)) {
    cat("Fit:")
    print(call)
    cat("\n")
  }
  pq <- x$test
  mtests <- cbind(pq$coefficients, pq$sigma, pq$tstat, pq$pvalues)
  error <- attr(pq$pvalues, "error")
  pname <- switch(x$alternative, less = paste("Pr(<", ifelse(x$df == 
                                                           0, "z", "t"), ")", sep = ""), greater = paste("Pr(>", 
                                                                                                          ifelse(x$df == 0, "z", "t"), ")", sep = ""), two.sided = paste("Pr(>|", 
                                                                                                                                                                        ifelse(x$df == 0, "z", "t"), "|)", sep = ""))
  colnames(mtests) <- c("Estimate", "Std. Error", ifelse(x$df == 
                                                       0, "z value", "t value"), pname)
  type <- pq$type
  if (!is.null(error) && error > .Machine$double.eps) {
    sig <- which.min(abs(1/error - (10^(1:10))))
    sig <- 1/(10^sig)
  }
  else {
    sig <- .Machine$double.eps
  }
  cat("Linear Hypotheses:\n")
  alt <- switch(x$alternative, two.sided = "==", less = ">=", 
                greater = "<=")
  rownames(mtests) <- paste(rownames(mtests), alt, x$rhs)
  printCoefmat(mtests, digits = digits, has.Pvalue = TRUE, 
               P.values = TRUE, eps.Pvalue = sig)
  cat("Degrees of Freedom: ", x$df, "\n") #our new line
  switch(type, univariate = cat("(Univariate p values reported)"), 
         `single-step` = cat("(Adjusted p values reported -- single-step method)"), 
         Shaffer = cat("(Adjusted p values reported -- Shaffer method)"), 
         Westfall = cat("(Adjusted p values reported -- Westfall method)"), 
         cat("(Adjusted p values reported --", type, "method)"))
  cat("\n\n")
  invisible(x)
}

示例结果:

lmod <- lm(Fertility ~ ., data = swiss)
K <- diag(length(coef(lmod)))[-1,]
rownames(K) <- names(coef(lmod))[-1]
glht(lmod, linfct = K) |> summary() |> print()

     Simultaneous Tests for General Linear Hypotheses

Fit: lm(formula = Fertility ~ ., data = swiss)

Linear Hypotheses:
                      Estimate Std. Error t value Pr(>|t|)    
Agriculture == 0      -0.17211    0.07030  -2.448   0.0793 .  
Examination == 0      -0.25801    0.25388  -1.016   0.7847    
Education == 0        -0.87094    0.18303  -4.758   <0.001 ***
Catholic == 0          0.10412    0.03526   2.953   0.0233 *  
Infant.Mortality == 0  1.07705    0.38172   2.822   0.0325

<details>
<summary>英文:</summary>

The most reliable way to find the possible arguments is to look into the function code. The summary function returns a list object, what governs what&#39;s printed is the `print()` function, so that&#39;s what we want to analize. 

But `print()` is a _generic function_, this is an _Object Oriented Programming_ that basically means &quot;a function that has different methods for each type of object it can receive&quot;. Running the code `print` gets us:

    function (x, ...) 
    UseMethod(&quot;print&quot;)

So we can&#39;t access the specific method of `print()` that it&#39;s used with a glht summary. To do that, we can either use debugging, or use the `sloop` package:

    sloop::s3_methods_generic(&#39;print&#39;)
    
    # A tibble: 403 &#215; 4
       generic class       visible source             
       &lt;chr&gt;   &lt;chr&gt;       &lt;lgl&gt;   &lt;chr&gt;              
     1 print   aareg       FALSE   registered S3method
     2 print   abbrev      FALSE   registered S3method
     3 print   acf         FALSE   registered S3method
     4 print   all_vars    FALSE   registered S3method
     5 print   anova       FALSE   registered S3method
     6 print   Anova       FALSE   registered S3method
     7 print   anova.loglm FALSE   registered S3method
     8 print   any_vars    FALSE   registered S3method
     9 print   aov         FALSE   registered S3method
    10 print   aovlist     FALSE   registered S3method
    # ℹ 393 more rows

These are all the methods that you have installed for `print()`. Now select the ones that have something to do with glht:

    sloop::s3_methods_generic(&#39;print&#39;) |&gt; filter(grepl(&#39;glht&#39;, class))

    # A tibble: 3 &#215; 4
      generic class        visible source             
      &lt;chr&gt;   &lt;chr&gt;        &lt;lgl&gt;   &lt;chr&gt;              
    1 print   confint.glht FALSE   registered S3method
    2 print   glht         FALSE   registered S3method
    3 print   summary.glht FALSE   registered S3method

Thus, we want the code for the method `print.summary.glht()` (this is the default syntax for methods, _function.class_):

    sloop::s3_get_method(&#39;print.summary.glht&#39;)

    function (x, digits = max(3, getOption(&quot;digits&quot;) - 3), ...) 
    {
        cat(&quot;\n\t&quot;, &quot;Simultaneous Tests for General Linear Hypotheses\n\n&quot;)
        if (!is.null(x$type))
    ... #I omitted the rest of the function

Now we can see that the arguments are `x`, `digits` (that are globally defined), and `...` (which aren&#39;t used anywhere in the method). So, in conclusion, there isn&#39;t an argument to display the degrees of freedom.

But, now that you have access to the function&#39;s code, you can alter it yourself, adding `cat(&quot;Degrees of Freedom: &quot;, x$df, &quot;\n&quot;)` near the end, and saving it with the same name:

    print.summary.glht &lt;- function (x, digits = max(3, getOption(&quot;digits&quot;) - 3), ...){
      cat(&quot;\n\t&quot;, &quot;Simultaneous Tests for General Linear Hypotheses\n\n&quot;)
      if (!is.null(x$type)) 
        cat(&quot;Multiple Comparisons of Means:&quot;, x$type, &quot;Contrasts\n\n\n&quot;)
      call &lt;- if (isS4(x$model)) 
        x$model@call
      else x$model$call
      if (!is.null(call)) {
        cat(&quot;Fit: &quot;)
        print(call)
        cat(&quot;\n&quot;)
      }
      pq &lt;- x$test
      mtests &lt;- cbind(pq$coefficients, pq$sigma, pq$tstat, pq$pvalues)
      error &lt;- attr(pq$pvalues, &quot;error&quot;)
      pname &lt;- switch(x$alternative, less = paste(&quot;Pr(&lt;&quot;, ifelse(x$df == 
                                                                   0, &quot;z&quot;, &quot;t&quot;), &quot;)&quot;, sep = &quot;&quot;), greater = paste(&quot;Pr(&gt;&quot;, 
                                                                                                                 ifelse(x$df == 0, &quot;z&quot;, &quot;t&quot;), &quot;)&quot;, sep = &quot;&quot;), two.sided = paste(&quot;Pr(&gt;|&quot;, 
                                                                                                                                                                                ifelse(x$df == 0, &quot;z&quot;, &quot;t&quot;), &quot;|)&quot;, sep = &quot;&quot;))
      colnames(mtests) &lt;- c(&quot;Estimate&quot;, &quot;Std. Error&quot;, ifelse(x$df == 
                                                               0, &quot;z value&quot;, &quot;t value&quot;), pname)
      type &lt;- pq$type
      if (!is.null(error) &amp;&amp; error &gt; .Machine$double.eps) {
        sig &lt;- which.min(abs(1/error - (10^(1:10))))
        sig &lt;- 1/(10^sig)
      }
      else {
        sig &lt;- .Machine$double.eps
      }
      cat(&quot;Linear Hypotheses:\n&quot;)
      alt &lt;- switch(x$alternative, two.sided = &quot;==&quot;, less = &quot;&gt;=&quot;, 
                    greater = &quot;&lt;=&quot;)
      rownames(mtests) &lt;- paste(rownames(mtests), alt, x$rhs)
      printCoefmat(mtests, digits = digits, has.Pvalue = TRUE, 
                   P.values = TRUE, eps.Pvalue = sig)
      cat(&quot;Degrees of Freedom: &quot;, x$df, &quot;\n&quot;) #our new line
      switch(type, univariate = cat(&quot;(Univariate p values reported)&quot;), 
             `single-step` = cat(&quot;(Adjusted p values reported -- single-step method)&quot;), 
             Shaffer = cat(&quot;(Adjusted p values reported -- Shaffer method)&quot;), 
             Westfall = cat(&quot;(Adjusted p values reported -- Westfall method)&quot;), 
             cat(&quot;(Adjusted p values reported --&quot;, type, &quot;method)&quot;))
      cat(&quot;\n\n&quot;)
      invisible(x)
    }

**Example of outcome:**

    lmod &lt;- lm(Fertility ~ ., data = swiss)
    K &lt;- diag(length(coef(lmod)))[-1,]
    rownames(K) &lt;- names(coef(lmod))[-1]
    glht(lmod, linfct = K) |&gt; summary() |&gt; print()
    
    	 Simultaneous Tests for General Linear Hypotheses
    
    Fit: lm(formula = Fertility ~ ., data = swiss)
    
    Linear Hypotheses:
                          Estimate Std. Error t value Pr(&gt;|t|)    
    Agriculture == 0      -0.17211    0.07030  -2.448   0.0793 .  
    Examination == 0      -0.25801    0.25388  -1.016   0.7847    
    Education == 0        -0.87094    0.18303  -4.758   &lt;0.001 ***
    Catholic == 0          0.10412    0.03526   2.953   0.0233 *  
    Infant.Mortality == 0  1.07705    0.38172   2.822   0.0325 *  
    ---
    Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
    Degrees of Freedom:  41 #our new line
    (Adjusted p values reported -- single-step method)





</details>



huangapple
  • 本文由 发表于 2023年5月17日 18:31:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76271134.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定