简体   繁体   English

是否有一种简单的方法可以基于多个点计算线性回归斜率?

[英]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.

相关问题 计算线性回归线的斜率 - Calculate the slope of a linear regression line 具有无限斜率的线性回归 - Linear regression with infinite slope 具有指定斜率的线性回归 - Linear regression with specified slope 通过线性回归计算每天(组)中每个变量的斜率 - Calculate the slope from a linear regression for each variable for each day (group) 如何计算R中线性回归模型中斜率的95%置信区间 - How to calculate the 95% confidence interval for the slope in a linear regression model in R 如何从线性回归分析中计算斜率? - How can I calculate the slope from a linear regression analysis? R:计算线性回归并获得“数据子集”的斜率 - R: Calculate linear regression and get slope for “a subset of data” 测试简单线性回归中的斜率是否等于R中的给定常数 - Test if the slope in simple linear regression equals to a given constant in R 线性回归[R]:如何根据分类变量的出现为同一预测变量计算多个系数 - Linear regression [R]: how to calculate multiple coefficients for the same predictor based on the occurrence of a categorical variable 有什么方法可以计算 lm() 多元线性回归模型中预测变量的 f 平方(作为效应大小)? - is there any way to calculate f-squared (as an effect size) for a predictor within an lm() multiple linear regression model?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM