创建线性或非线性模型的(分组)摘要以加入 table 并预测值
Creating a (grouped) summary of linear or nonlinear models to join to a table and predict values
我有一个包含三列的 table:x 和 y,以及 id。我想为每个 id 创建一个线性模型。
id x y
1 a 1 2
2 b 5 10
3 a 8 16
4 b 1 2
5 a 6 12
6 c 9 18
7 a 2 4
8 a 9 18
9 b 1 2
10 b 6 12
11 b 10 20
12 c 12 24
13 c 2 4
14 c 4 8
15 c 5 10
我可以使用 split/apply 或使用 nlme 的 lmList
函数来做到这一点。我将如何使用 id 创建一个摘要 table,并将其各自的线性模型存储在一个小摘要 table 中?
另外,我如何将摘要 table 连接回上述数据框(或另一个带有 ID 列和 x 列的数据框)?那么,是否也可以使用连接的线性模型并使用给定行中的相应 x 值预测结果
# Representation of what it would look like to join and predict the linear model
id x lm
1 a 1 <first lm here>
2 b 5 <second lm here>
对于给定的 x 值,是否可以使用上面的示例使用相应的 lm 来预测 y?这也可以扩展到其他模型,如 knn3
和 loess
?
尝试使用这种方法。只要你知道你的 id 的顺序,你就可以在 tibble 中定义它们,并将它们各自的线性模型存储在列表列中。
进一步解释:定义summarydata$lm
的map
命令根据[=16的值将df1
拆分为三个独立的数据帧=],然后将线性模型拟合到这些数据帧中的每一个。然后将生成的模型对象存储在 summarydata$lm
.
中
library(tidyverse)
# Reproducing your data
df1 <- tibble(
id = c("a", "b", "a", "b", "a", "c", "a", "a", "b", "b", "b", "c", "c", "c", "c"),
x = c(1, 5, 8, 1, 6, 9, 2, 9, 1, 6, 10, 12, 2, 4, 5),
y = c(2, 20, 26, 2, 12, 18, 4, 18, 2, 12, 20, 24, 4, 8, 10)
)
summarydata <- tibble(
id = c("a", "b", "c"),
x = c(1, 5, 7),
lm = map(group_split(df1, id), ~ lm(y ~ x, data = .))
)
然后,要获得每个线性模型的预测,我们可以在 mutate 中使用另一个 map 命令。这从 summarydata
获取每个线性模型和 x
的每个值,并使用 predict
.
计算 y 的预测值
summarydata %>%
mutate(
prediction = map2_dbl(lm, x, ~ predict(.x, newdata = tibble(x = .y)))
)
输出:
# A tibble: 3 x 4
id x lm prediction
<chr> <dbl> <list> <dbl>
1 a 1 <lm> 1.69
2 b 5 <lm> 12.0
3 c 7 <lm> 14
我有一个包含三列的 table:x 和 y,以及 id。我想为每个 id 创建一个线性模型。
id x y
1 a 1 2
2 b 5 10
3 a 8 16
4 b 1 2
5 a 6 12
6 c 9 18
7 a 2 4
8 a 9 18
9 b 1 2
10 b 6 12
11 b 10 20
12 c 12 24
13 c 2 4
14 c 4 8
15 c 5 10
我可以使用 split/apply 或使用 nlme 的 lmList
函数来做到这一点。我将如何使用 id 创建一个摘要 table,并将其各自的线性模型存储在一个小摘要 table 中?
另外,我如何将摘要 table 连接回上述数据框(或另一个带有 ID 列和 x 列的数据框)?那么,是否也可以使用连接的线性模型并使用给定行中的相应 x 值预测结果
# Representation of what it would look like to join and predict the linear model
id x lm
1 a 1 <first lm here>
2 b 5 <second lm here>
对于给定的 x 值,是否可以使用上面的示例使用相应的 lm 来预测 y?这也可以扩展到其他模型,如 knn3
和 loess
?
尝试使用这种方法。只要你知道你的 id 的顺序,你就可以在 tibble 中定义它们,并将它们各自的线性模型存储在列表列中。
进一步解释:定义summarydata$lm
的map
命令根据[=16的值将df1
拆分为三个独立的数据帧=],然后将线性模型拟合到这些数据帧中的每一个。然后将生成的模型对象存储在 summarydata$lm
.
library(tidyverse)
# Reproducing your data
df1 <- tibble(
id = c("a", "b", "a", "b", "a", "c", "a", "a", "b", "b", "b", "c", "c", "c", "c"),
x = c(1, 5, 8, 1, 6, 9, 2, 9, 1, 6, 10, 12, 2, 4, 5),
y = c(2, 20, 26, 2, 12, 18, 4, 18, 2, 12, 20, 24, 4, 8, 10)
)
summarydata <- tibble(
id = c("a", "b", "c"),
x = c(1, 5, 7),
lm = map(group_split(df1, id), ~ lm(y ~ x, data = .))
)
然后,要获得每个线性模型的预测,我们可以在 mutate 中使用另一个 map 命令。这从 summarydata
获取每个线性模型和 x
的每个值,并使用 predict
.
summarydata %>%
mutate(
prediction = map2_dbl(lm, x, ~ predict(.x, newdata = tibble(x = .y)))
)
输出:
# A tibble: 3 x 4
id x lm prediction
<chr> <dbl> <list> <dbl>
1 a 1 <lm> 1.69
2 b 5 <lm> 12.0
3 c 7 <lm> 14