[英]Is there a simple way to calculate the linear regression slope based on multiple points?
data <- data.frame(Year1 = c(4, 2), Year2 = c(0, 10), Year3 = c(5, 6), Year4 = c(18, 4))
Given the 2 rows/observations above which contains 4 years/columns. 给定上面包含2年/列的2行/观测值。 I'd like to get R to calculate the slope of the linear regression line based on all 4 points for each observation.
我想让R基于每个观察的所有4个点计算线性回归线的斜率。
The slope value should appear in a new column to the right of the data frame. 斜率值应出现在数据框右侧的新列中。
slope_data <- data.frame(Year1 = c(4, 2), Year2 = c(0, 10), Year3 = c(5, 6), Year4 = c(18, 4), Slope = c(5, 5))
I was wondering if there was a simple function or package that could achieve this? 我想知道是否有一个简单的函数或程序包可以实现这一目标?
Based on the comments, this will be needed for more than two rows. 根据评论,这将需要两行以上。 You can use
lm
to get the needed slope for one row and use sapply
to get it for all rows. 您可以使用
lm
获取一行的所需斜率,并使用sapply
获取所有行的斜率。
Slope = function(x) {
TempDF = data.frame(x, year=1:ncol(data))
lm(x ~ year, data=TempDF)$coefficients[2]
}
TData = as.data.frame(t(data))
data$slope = sapply(TData, Slope)
data
Year1 Year2 Year3 Year4 slope
1 4 0 5 18 4.7
2 2 10 6 4 0.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.