简体   繁体   中英

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. I'd like to get R to calculate the slope of the linear regression line based on all 4 points for each observation.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM