计算R中表格每一行的线性趋势线

use*_*656 3 regression r trendline

是否有可能在不使用循环的情况下对数据帧的每一行进行线性回归?趋势线的输出(截距+斜率)应作为新列添加到原始数据框中。

为了更清楚地表达我的意图,我准备了一个非常小的数据示例:

day1 <- c(1,3,1)
day2 <- c(2,2,1)
day3 <- c(3,1,5)
output.intercept <- c(0,4,-1.66667)
output.slope <- c(1,-1,2)
data <- data.frame(day1,day2,day3,output.intercept,output.slope)
Run Code Online (Sandbox Code Playgroud)

输入变量为day1-3;假设这些是不同商店连续 3 天的销售额。我想要做的是计算 3 行的线性趋势线,并将输出参数添加到原始表(请参阅 output.intercept + output.slope)作为新列。

该解决方案在计算时间方面应该非常高效,因为实际数据帧有许多 100k 行。

最好的,克里斯托夫

Rol*_*and 5

design.mat <- cbind(1,1:3)
response.mat <- t(data[,1:3])

reg <- lm.fit(design.mat, response.mat)$coefficients
data <- cbind(data, t(reg))
#  day1 day2 day3 output.intercept output.slope        x1 x2
#1    1    2    3          0.00000            1  0.000000  1
#2    3    2    1          4.00000           -1  4.000000 -1
#3    1    1    5         -1.66667            2 -1.666667  2
Run Code Online (Sandbox Code Playgroud)

但是,如果您有大量数据,由于内存限制,可能需要循环。如果是这种情况,我将使用长格式 data.table 并使用包的by语法进行循环。