我一直在尝试(几天来)“自动化”几个线性回归,它们使用相同的x轴数据(“甲烷”),但y轴不同(第1天、第10天、第16天等)。从每个回归中,我想提取截距和斜率,并将它们写在每个相应的列下(第1天到72天)。我仍然不知道哪种方法更适合循环或s/lapply。
示例(数据框名为"raw_standards"):
Methane 1 10 16 62 72
224.62 1490700 1423400 2475400 2063300 1819650
449.23 3297100 2878950 4980300 4078800 3701750
842.32 4181900 5292200 10718500 8247400 7566600
2246.18 9211500 12535000 25439000 19867500 16443000
4492.36 29228000 27567000 49345000 39328000 30743000 我的当前for循环如下:
for (i in raw_standards[,2:6]) {
y = raw_standards [,3:20]
lm(y ~ raw_standards$'uM Methane', raw_standards)
}我还尝试使用lapply:
lapply (raw_standards [ , 2:6],
lm(raw_standards [ , 2:6] ~ raw_standards$'uM Methane',raw_standards))任何有助于理解如何正确编写正确代码的帮助都是非常感谢的。
发布于 2015-12-18 20:14:59
我喜欢用管道做这类事情。来自hadley的三个包的出色组合将会完成这项工作。
df <- data.frame(Methane = rnorm(30),Day1 = rnorm(30),Day2 = rnorm(30),Day3 = rnorm(30))
library(tidyr)
library(dplyr)
library(purrr)
df %>% gather(Variable,value,-Methane) %>% split(.$Variable) %>%
map(~ lm(value ~ Methane, data = .)) %>%
map("coefficients") 第一步: gather函数将数据转换为长格式。
第二步:将数据帧拆分成一个数据帧列表。
第三步: map在列表的所有元素上构建线性模型(与lapply相同)
要进一步澄清,请参阅这些包的包小插页,这些包写得非常好。上述代码的输出为:
$Day1
(Intercept) Methane
0.17664660 -0.07090221
$Day2
(Intercept) Methane
0.03615358 0.24230124
$Day3
(Intercept) Methane
0.1662604 -0.2836147 https://stackoverflow.com/questions/34304306
复制相似问题