gpt4 book ai didi

r - 使用Data.Table包按组拟合模型

转载 作者:行者123 更新时间:2023-12-04 14:43:36 25 4
gpt4 key购买 nike

如何使用data.table语法按组拟合多个模型?我希望我的输出是一个data.frame,其中每个“按组”都有列,而每个模型拟合都有一列。目前,我可以使用dplyr包来执行此操作,但不能在data.table中执行此操作。

# example data frame
df <- data.table(
id = sample(c("id01", "id02", "id03"), N, TRUE),
v1 = sample(5, N, TRUE),
v2 = sample(round(runif(100, max = 100), 4), N, TRUE)
)

# equivalent code in dplyr
group_by(df, id) %>%
do( model1= lm(v1 ~v2, .),
model2= lm(v2 ~v1, .)
)

# attempt in data.table
df[, .(model1 = lm(v1~v2, .SD), model2 = lm(v2~v1, .SD) ), by = id ]

# Brodie G's solution
df[, .(model1 = list(lm(v1~v2, .SD)), model2 = list(lm(v2~v1, .SD))), by = id ]

最佳答案

尝试:

df[, .(model1 = list(lm(v1~v2, .SD)), model2 = list(lm(v2~v1, .SD))), by = id ]

或更惯用的:
formulas <- list(v1~v2, v2~v1)
df[, lapply(formulas, function(x) list(lm(x, data=.SD))), by=id]

关于r - 使用Data.Table包按组拟合模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29420674/

25 4 0