将回归系数存储在R data.table中

时间:2018-09-05 17:23:57

标签: r data.table regression

我想进行回归并将系数存储在data.table中。这是一个最小的示例:

library(data.table)
library(MASS)

dt <- as.data.table(iris)
dt[, c("coef1", "coef2") := rlm(Sepal.Length ~ Petal.Length)$coef]
dt

但是,它循环输出,因此coef1和coef2在每一行上都相同,但是两个系数在每隔一行上显示。

此示例显示了我的外观,但这并不是最佳选择,因为它需要运行两次回归:

dt <- as.data.table(iris)
dt[, `:=`("coef1"=rlm(Sepal.Length ~ Petal.Length)$coef[1], "coef2"=rlm(Sepal.Length ~ Petal.Length)$coef[2])]
dt

1 个答案:

答案 0 :(得分:4)

您似乎想按行存储。试试这个:

library(data.table)
library(MASS)
dt <- as.data.table(iris)
dt[, c("coef1", "coef2") := as.list(rlm(Sepal.Length ~ Petal.Length)$coef)][]
dt
# output
     Sepal.Length Sepal.Width Petal.Length Petal.Width   Species    coef1     coef2
  1:          5.1         3.5          1.4         0.2    setosa 4.300878 0.4097214
  2:          4.9         3.0          1.4         0.2    setosa 4.300878 0.4097214
  3:          4.7         3.2          1.3         0.2    setosa 4.300878 0.4097214
  4:          4.6         3.1          1.5         0.2    setosa 4.300878 0.4097214
  5:          5.0         3.6          1.4         0.2    setosa 4.300878 0.4097214
 ---                                                                               
146:          6.7         3.0          5.2         2.3 virginica 4.300878 0.4097214
147:          6.3         2.5          5.0         1.9 virginica 4.300878 0.4097214
148:          6.5         3.0          5.2         2.0 virginica 4.300878 0.4097214
149:          6.2         3.4          5.4         2.3 virginica 4.300878 0.4097214
150:          5.9         3.0          5.1         1.8 virginica 4.300878 0.4097214