我有一个数据框,我想按小时列出。
wkd = data.frame(hour = c(0,0,1,1,2,2),
distance = c(5.69,0.56,6.90,1.81,9.88,1.56),
time = c(23,3,17,7,32,7),
fare = c(18.35,5.39,18.46,12.90,28.08,5.81))
hour distance time fare
1 0 5.69 23 18.35
2 0 0.56 3 5.39
3 1 6.90 17 18.46
4 1 1.81 7 12.90
5 2 9.88 32 28.08
6 2 1.56 7 5.81
创建列表后,我想通过fare ~ time + distance
循环一个lm函数
我试图在数据框上使用apply但没有成功:
a = apply(wkd,2,as.list)
How to create a loop for a linear model in R 一旦我按小时列表格式的数据框,这看起来与我想要的相关。
创建列表后,我想循环一个lm() on fare ~ distance + time
,最后,我希望系数为24个线性方程的数据框
我想要的最终输出应该如下所示:
hour distance time intercept
1 0 2.25 0.36 2.35
2 1 3.25 0.41 3.45
3 2 4.56 0.22 5.22
如果我正确理解您的问题,您希望在每小时运行数据的线性模型。
如果就是这样,我们可以使用split()
创建列表,然后使用sapply
来运行模型
wkd = split(wkd, f=wkd$hour)
res = sapply(wkd,function(x) lm(fare~ distance + time,data=x)$coefficients)
#Expected output
t(res)
一个tidyverse
可能是:
wkd %>%
group_by(hour) %>%
do(model = lm(fare ~ time + distance, data = .)$coefficients) %>%
tidy(model) %>%
mutate(names = ifelse(names == "(Intercept)", "intercept", names)) %>%
spread(names, x) %>%
select(hour, intercept, everything())
hour intercept distance time
<dbl> <dbl> <dbl> <dbl>
1 0 3.45 NA 0.648
2 1 9.01 NA 0.556
3 2 -0.426 NA 0.891