Reputation: 504
I would like to run a regression and store the coefficients in a data.table. Here is a minimal example:
library(data.table)
library(MASS)
dt <- as.data.table(iris)
dt[, c("coef1", "coef2") := rlm(Sepal.Length ~ Petal.Length)$coef]
dt
However it recycles the output so the coef1 and coef2 are the same on each line, but the two coefficients show up on every other line.
This example shows how I would like it to look, but it is not optimal because it requires running the regression twice:
dt <- as.data.table(iris)
dt[, `:=`("coef1"=rlm(Sepal.Length ~ Petal.Length)$coef[1], "coef2"=rlm(Sepal.Length ~ Petal.Length)$coef[2])]
dt
Upvotes: 4
Views: 113
Reputation: 6768
It looks like you want to store by row. Try this:
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
Upvotes: 4