gpt4 book ai didi

r - ddply 用于 R 中的回归

转载 作者:行者123 更新时间:2023-12-04 11:31:01 25 4
gpt4 key购买 nike

我有一个数据框,其中包含 100 个城市(由代码给出)的“输出”、平均温度、湿度和时间(以 24 个因子给出,非连续)数据。我想应用回归公式根据温度、湿度和时间数据预测每个城市的输出。我希望得到 100 个不同的回归模型。我使用了 ddply 函数并在 this thread 的帮助下想出了以下代码行.

df = ddply(data, "city", function(x) coefficients(lm(output~temperature+humidity, data=x)))

此代码适用于数字数据、温度和湿度。但是当我添加时区因子数据(这是 23 个因子变量)时,我收到一个错误:
df = ddply(data, "city", function(x) coefficients(lm(output~temperature+humidity+time, data=x)))

“错误:对比只能应用于具有 2 个或更多级别的因素”

有人知道为什么是这样吗?这是我的数据框的一个示例块:
city    temperature   humidity   time   output
11 51 34 01 201
11 43 30 02 232
11 55 50 03 253
11 64 54 10 280
22 21 52 11 321
22 43 65 04 201
22 51 66 09 211
22 51 78 16 199
05 45 70 01 202
05 51 54 10 213

所以我想要这里三个城市的三个模型,基于温度、湿度和时间因素。

最佳答案

通过使用 ddply , 您申请 lm到数据框的子集,其中每个子集对应于某个城市。完整数据集中的一些城市似乎只有一条记录。对于这种情况,统计分析显然没有意义,但是lm会给你一些答案,但如果模型中有一个因子变量,它会抛出一个错误。

作为一种解决方法,您可以检查匿名函数中的行数:

ddply(d,'city',function(x) if (nrow(x)==1) return() else coefficients(lm(output~temperature+humidity+time, data=x)))

哪里 d是您的样本集的略微修改版本,其中我更改了最后一行中城市的 id 以确保某些城市只有一条记录:
d <- structure(list(city = c(11, 11, 11, 11, 22, 22, 22, 22, 5, 7), temperature = c(51L, 43L, 55L, 64L, 21L, 43L, 51L, 51L, 45L,     51L), humidity = c(34L, 30L, 50L, 54L, 52L, 65L, 66L, 78L,     70L, 54L), time = structure(c(1L, 2L, 3L, 6L, 7L, 4L, 5L,     8L, 1L, 6L), .Label = c("1", "2", "3", "4", "9", "10", "11",     "16"), class = "factor"), output = c(201L, 232L, 253L, 280L,     321L, 201L, 211L, 199L, 202L, 213L)), .Names = c("city", "temperature", "humidity", "time", "output"), row.names = c(NA, -10L), class = "data.frame")

你也可以使用这个基本的 R 代码代替 ddply :
L <- split(d,d$city)

L2 <- lapply(L,function(x) {
if (nrow(x)==1)
return()
else
coefficients(lm(output~temperature+humidity+time, data=x))
})

M <- do.call(rbind,L2)
df <- as.data.frame(M)

这段代码比较冗长,但在出现问题行为时更容易检查和分析它。

关于r - ddply 用于 R 中的回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28733432/

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