r - 如何计算不同列中每一行的斜率和截距
问题描述
我正在尝试计算数据框中不同列中每一行的斜率和截距。输出(截距和斜率)应作为新列添加到原始数据框中。
为了尽可能清楚我想要实现的目标,我在下面提供了一些数据:
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 行)。
解决方案
好吧,您的数据不是“整洁”的格式,这使得大多数内置函数难以使用。您可以使用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, .)
推荐阅读
- python - 如何使用 Python 正确编码/解码 excel 文件?
- javascript - 何时使用 Vue 拆分成组件?
- java - 生菜无法弄清楚多级复制拓扑
- r - 如何计算数组和矩阵之间的距离
- c++ - RCPP - 没有用于调用“转换”的匹配函数
- python - 如何在 numpy 中获取两个索引数组之间的矩阵元素?
- angular - 无法读取underfined的属性
- c# - 序列化 LambdaExpression 到字符串和从字符串中保存以保存在数据库中
- azure-devops - 带有模板的 azure devops yaml 管道不签出引用的存储库
- python - 在列表中查找最大值及其索引 - 不断得到错误的索引