gpt4 book ai didi

r - 如何使用存储在 data.table 或 tibble 中的线性模型添加预测列?

转载 作者:行者123 更新时间:2023-12-01 23:36:48 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





using lm in list column to predict new values using purrr

(1 个回答)


2年前关闭。




我在一张表中存储了许多线性模型。现在我想在到达行中使用模型来预测一个单一的 y 值,给定相应行中的一个单一 x 值。

难点在于data.table和tidyverse提取表中模型的方式。 predict.lm 函数需要类“lm”对象,在类“list”对象内。

library(data.table)

model1 <- lm( y~x, data= data.table( x=c(1,2,3,4) , y=c(1,2,1,2) ))
model2 <- lm( y~x, data= data.table( x=c(1,2,3,4) , y=c(1,2,3,3) ))

model_dt <- data.table( id = c(1,2), model = list(model1, model2), x = c(3,3))

现在 model_dt 包含线性模型和所需的 x 值。

逐行预测效果很好:
predict.lm( model_dt[1]$model[[1]], model_dt[1])  # yields 1.6
predict.lm( model_dt[2]$model[[1]], model_dt[2]) # yields 2.6

但是直接加一列会报错:
model_dt[, pred_y := predict.lm( model , x )]         # ERROR
model_dt[, pred_y := predict.lm( model , x ), by=id] # ERROR

================================================== ==============

tidyverse 中的相同设置:
library(tidyverse)

model1 <- lm( y~x, data= tibble( x=c(1,2,3,4) , y=c(1,2,1,2) ))
model2 <- lm( y~x, data= tibble( x=c(1,2,3,4) , y=c(1,2,3,3) ))

model_dt <- tibble( id = c(1,2), model = list(model1, model2), x = c(3,3))

predict.lm( model_dt[1,]$model[[1]], model_dt[1,]) # yields 1.6
predict.lm( model_dt[2,]$model[[1]], model_dt[2,]) # yields 2.6

添加带有 mutate 的变量失败:
model_dt %>% mutate( pred_y = predict.lm( model, x ) )  # ERROR

似乎原因之一是,表内“模型”列内的模型无法提取为类“lm”对象,但在 data.table 或 mutate 函数中使用 model[[1]] 总是指模型在第 1 行。
class( model_dt[1,]$model )      # results in class "list"
class( model_dt[1,]$model[[1]] ) # results in class "lm"

结果应该是如下表:
   id model x pred_y
1: 1 <lm> 3 1.6
2: 2 <lm> 3 2.6

我相信有一个简单的解决方案,并且会对输入感到非常高兴。 map() 或 lapply() 的可能解决方案也有同样的问题。非常感谢。

================================================== ====================

编辑:除了问题 using lm in list column to predict new values using purrr 之外,此问题还要求在 data.table 中提供解决方案

最佳答案

tidyverse ,我们使用 map2循环遍历“模型”,对应的“x”值,在 predict 中传递新数据作为 data.frametibble

library(tidyverse)
model_dt %>%
mutate(pred_y = map2_dbl(model, x, ~ predict.lm(.x, tibble(x = .y))))
# A tibble: 2 x 4
# id model x pred_y
# <dbl> <list> <dbl> <dbl>
#1 1 <lm> 3 1.6
#2 2 <lm> 3 2.60

或使用 data.table (对象)与 Map
model_dt[,  pred_y := unlist(Map(function(mod, y) 
predict.lm(mod, data.frame(x = y)), model, x)), id][]
# id model x pred_y
#1: 1 <lm> 3 1.6
#2: 2 <lm> 3 2.6

关于r - 如何使用存储在 data.table 或 tibble 中的线性模型添加预测列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56878025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com