【问题标题】:R command that returns the components of a function?返回函数组件的R命令?
【发布时间】:2014-07-02 18:05:18
【问题描述】:

假设我有fit=lm(y~x)。显示fit 的组件的 R 命令是什么?我记得如果我运行mystery_Rcommand(fit),那么控制台会返回一个组件列表,例如“fitted.values”、“residuals”、“coefficients”等。知道这些组件将使我能够执行fit$fitted.values 和看看拟合值和什么不是。但我只是不记得那个 R 命令是什么。有人可以帮忙吗?

【问题讨论】:

  • 或许,您正在寻找?str?unclass
  • 我经常使用attributes(fit)

标签: r


【解决方案1】:

fitted(), resid(), coef(), ..., 将提取组件。 methods(class = "lm") 会告诉你更多。

str() 将向您展示模型拟合的结构,列表的组件。 ?lm 将告诉您 lm() 返回的对象中应包含哪些组件。

一个例子,来自?lm

## Annette Dobson (1990) "An Introduction to Generalized Linear Models".
## Page 9: Plant Weight Data.
ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
group <- gl(2, 10, 20, labels = c("Ctl","Trt"))
weight <- c(ctl, trt)
lm.D9 <- lm(weight ~ group)

str(lm.D9)
coef(lm.D9)
fitted(lm.D9)

制作(编辑):

> str(lm.D9)
List of 13
 $ coefficients : Named num [1:2] 5.032 -0.371
  ..- attr(*, "names")= chr [1:2] "(Intercept)" "groupTrt"
 $ residuals    : Named num [1:20] -0.862 0.548 0.148 1.078 -0.532 ...
  ..- attr(*, "names")= chr [1:20] "1" "2" "3" "4" ...
 $ effects      : Named num [1:20] -21.674 -0.83 0.197 1.127 -0.483 ...
  ..- attr(*, "names")= chr [1:20] "(Intercept)" "groupTrt" "" "" ...
 $ rank         : int 2
 $ fitted.values: Named num [1:20] 5.03 5.03 5.03 5.03 5.03 ...
  ..- attr(*, "names")= chr [1:20] "1" "2" "3" "4" ...
 $ assign       : int [1:2] 0 1
 $ qr           :List of 5
....
> coef(lm.D9)
(Intercept)    groupTrt 
      5.032      -0.371 
> fitted(lm.D9)
    1     2     3     4     5     6     7     8     9    10    11    12    13 
5.032 5.032 5.032 5.032 5.032 5.032 5.032 5.032 5.032 5.032 4.661 4.661 4.661 
   14    15    16    17    18    19    20 
4.661 4.661 4.661 4.661 4.661 4.661 4.661

【讨论】:

  • summary(lm.D9) 也值得一看,但我通常使用str(lm.D9) 来解决问题中的特定问题
  • 听起来他们可能也只是使用names(fit) 来获取列表项的名称,而不一定是所有值。但所有这些功能在不同的时间都有用。
猜你喜欢
  • 2017-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-05
  • 2023-01-01
  • 1970-01-01
相关资源
最近更新 更多