【发布时间】:2021-09-08 05:43:19
【问题描述】:
我正在尝试为每个可能的变量组合找到 iris 数据集组之间的线性回归。由于这是一个玩具示例,因此很容易对每个变量集分别进行线性回归并将结果连接起来。但是,data.table 具有大量列,很难找到所有组之间的线性回归。
library(data.table)
dt = copy(iris)
setDT(dt)[, .(model1 = lm(Sepal.Length ~ Petal.Width, .SD)$coeff[2], model2 = lm(Petal.Width ~ Sepal.Length, .SD)$coeff[2]), by = Species]
Species model1 model2
1: setosa 0.9301727 0.08314444
2: versicolor 1.4263647 0.20935719
3: virginica 0.6508306 0.12141646
setDT(dt)[, .(model1 = lm(Sepal.Width ~ Petal.Length, .SD)$coeff[2], model2 = lm(Petal.Length ~ Sepal.Width, .SD)$coeff[2]), by = Species]
Species model1 model2
1: setosa 0.3878739 0.0814112
2: versicolor 0.3743068 0.8393782
3: virginica 0.2343482 0.6863153
setDT(dt)[, .(model1 = lm(Sepal.Width ~ Sepal.Length, .SD)$coeff[2], model2 = lm(Sepal.Length ~ Sepal.Width, .SD)$coeff[2]), by = Species]
Species model1 model2
1: setosa 0.7985283 0.6904897
2: versicolor 0.3197193 0.8650777
3: virginica 0.2318905 0.9015345
setDT(dt)[, .(model1 = lm(Petal.Width ~ Petal.Length, .SD)$coeff[2], model2 = lm(Petal.Length ~ Petal.Width, .SD)$coeff[2]), by = Species]
Species model1 model2
1: setosa 0.2012451 0.5464903
2: versicolor 0.3310536 1.8693247
3: virginica 0.1602970 0.6472593
与其分别对每组变量进行线性回归,是否可以使用 data.table 轻松地做到这一点?我想要的输出如下-
Species Variable1 Variable2 model1 model2
setosa Sepal.Length Petal.Width 0.9301727 0.08314444
versicolor Sepal.Length Petal.Width 1.4263647 0.20935719
virginica Sepal.Length Petal.Width 0.6508306 0.12141646
setosa Sepal.Width Petal.Length 0.3878739 0.0814112
versicolor Sepal.Width Petal.Length 0.3743068 0.8393782
virginica Sepal.Width Petal.Length 0.2343482 0.6863153
setosa Sepal.Width Sepal.Length 0.7985283 0.6904897
versicolor Sepal.Width Sepal.Length 0.3197193 0.8650777
virginica Sepal.Width Sepal.Length 0.2318905 0.9015345
setosa Petal.Width Petal.Length 0.2012451 0.5464903
versicolor Petal.Width Petal.Length 0.3310536 1.8693247
virginica Petal.Width Petal.Length 0.1602970 0.6472593
【问题讨论】:
标签: r data.table regression