如何创建带有键列的列表?

How to create a list with a key column?

我有一个要按小时列出的数据框。

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 函数

我尝试在数据框上使用应用但没有成功:

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