R:对数据进行多元线性回归 table
R: do multiple linear regressions in a data table
我有一个数据 table 看起来像这样(来自 CSV)概述了投票数据。我需要知道的是,通过对 votesneeded ~ dayuntilelection 进行线性回归,每年(平均)每天有多少票进来。斜率是每天收到的平均票数。
我如何 运行 按年份对该数据框进行线性回归函数?
date,year,daysuntilelection,votesneeded
2018-01-25,2018,9,40
2018-01-29,2018,5,13
2018-01-30,2018,4,-11
2018-02-03,2018,0,-28
2019-01-23,2019,17,81
2019-02-01,2019,8,-4
2019-02-09,2019,0,-44
2020-01-17,2020,22,119
2020-01-24,2020,15,58
2020-01-30,2020,9,12
2020-02-03,2020,5,-4
2020-02-07,2020,1,-12
2021-01-08,2021,29,120
2021-01-26,2021,11,35
2021-01-29,2021,8,17
2021-02-01,2021,5,-2
2021-02-03,2021,3,-8
2021-02-06,2021,0,-10
首选输出是一个看起来像这样的数据框
year averagevotesperday
2018 8.27
2019 7.40
2020 6.55
2021 4.60
注意:完整的数据集和分析位于 https://github.com/robhanssen/glenlake-elections,以供好奇。
你需要这样的东西吗?
library(dplyr)
dat |>
group_by(year) |>
summarize(
avgVoteDay = coef(lm(votesneeded ~ daysuntilelection))[2]
)
输出与您的略有不同:
# A tibble: 4 x 2
year avgvote_day
<int> <dbl>
1 2018 7.76
2 2019 7.40
3 2020 6.41
4 2021 4.74
我有一个数据 table 看起来像这样(来自 CSV)概述了投票数据。我需要知道的是,通过对 votesneeded ~ dayuntilelection 进行线性回归,每年(平均)每天有多少票进来。斜率是每天收到的平均票数。
我如何 运行 按年份对该数据框进行线性回归函数?
date,year,daysuntilelection,votesneeded
2018-01-25,2018,9,40
2018-01-29,2018,5,13
2018-01-30,2018,4,-11
2018-02-03,2018,0,-28
2019-01-23,2019,17,81
2019-02-01,2019,8,-4
2019-02-09,2019,0,-44
2020-01-17,2020,22,119
2020-01-24,2020,15,58
2020-01-30,2020,9,12
2020-02-03,2020,5,-4
2020-02-07,2020,1,-12
2021-01-08,2021,29,120
2021-01-26,2021,11,35
2021-01-29,2021,8,17
2021-02-01,2021,5,-2
2021-02-03,2021,3,-8
2021-02-06,2021,0,-10
首选输出是一个看起来像这样的数据框
year averagevotesperday
2018 8.27
2019 7.40
2020 6.55
2021 4.60
注意:完整的数据集和分析位于 https://github.com/robhanssen/glenlake-elections,以供好奇。
你需要这样的东西吗?
library(dplyr)
dat |>
group_by(year) |>
summarize(
avgVoteDay = coef(lm(votesneeded ~ daysuntilelection))[2]
)
输出与您的略有不同:
# A tibble: 4 x 2
year avgvote_day
<int> <dbl>
1 2018 7.76
2 2019 7.40
3 2020 6.41
4 2021 4.74