首页 > 解决方案 > 如何计算不同列中每一行的斜率和截距

问题描述

我正在尝试计算数据框中不同列中每一行的斜率和截距。输出(截距和斜率)应作为新列添加到原始数据框中。

为了尽可能清楚我想要实现的目标,我在下面提供了一些数据:

locations<-c("a","b","c")

proportion.I<-c(0.073846154, 0.079710145, 0.063218391)

proportion.II<-c(0.049773659, 0.033756955, 0.011237956)

proportion.III<-c(0.090322581, 0.100917431, 0.08051443)

abundance.I<-c(331,331,331)

abundance.II<-c(178,178,178)

abundance.III<-c(87,87,87)

output.slope<-c(5.539e-05, -4.665e-05, -2.819e-05)

output.intercept<-c(5.128e-02, 8.073e-02, 5.726e-02)

df<-data.frame(locations, proportion.I, proportion.II, proportion.III, abundance.I, abundance.II, abundance.III, output.slope, output.intercept)

*我的线性回归的“因”变量将是“比例”(第 2:4 行),预测变量(或自变量)将是“丰度”(第 5:7 行)。

标签: rrowlinear-regression

解决方案


好吧,您的数据不是“整洁”的格式,这使得大多数内置函数难以使用。您可以使用dplyr并将tidyr您的数据转换为共享,以便更轻松地进行分组回归。例如

library(dplyr)
library(tidyr)

df %>% 
  select(-starts_with("output")) %>%                   #drop "answers"
  pivot_longer(proportion.I:abundance.III) %>%         # convert to long format
  separate(name, into = c("var", "idx")) %>%           # get values from column names
  pivot_wider(names_from=var, values_from=value) %>%   # go back to wide
  nest(data=-locations) %>%                             
  mutate(reg = map(data, ~lm(abundance~proportion, .))) %>%   # do the regression
  mutate(intercept=map_dbl(reg, ~coefficients(.)[1]),         # get values form regression
         slope=map_dbl(reg, ~coefficients(.)[2]))

这与您提供的值相匹配,但根据您的描述,您似乎希望以另一种方式进行回归:~lm(proportion~abundance, .)


推荐阅读