R中回归的ddply
我有一个数据框架,它包含100个城市(由代码给出)的“输出”、“平均温度、湿度和时间(给定为24个因素,而不是连续的)数据。”。我想应用一个回归公式,根据温度、湿度和时间数据预测每个城市的产量。我希望得到100种不同的回归模型。我使用了ddply函数,并在的帮助下得出了以下代码行 此代码适用于数字数据、温度和湿度。但当我加入时区因子数据(23个因子变量)时,我得到一个错误:R中回归的ddply,r,regression,plyr,R,Regression,Plyr,我有一个数据框架,它包含100个城市(由代码给出)的“输出”、“平均温度、湿度和时间(给定为24个因素,而不是连续的)数据。”。我想应用一个回归公式,根据温度、湿度和时间数据预测每个城市的产量。我希望得到100种不同的回归模型。我使用了ddply函数,并在的帮助下得出了以下代码行 此代码适用于数字数据、温度和湿度。但当我加入时区因子数据(23个因子变量)时,我得到一个错误: df = ddply(data, "city", function(x) coefficients(lm(output~t
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")
这段代码比较冗长,但在出现问题行为时,检查和分析它要容易得多。在您的示例中,我找不到变量“output”。另外,你应该
dput
数据的再现性。哎哟,修正了。我不熟悉dput,但我会在以后的帖子中查看它。谢谢,太好了,谢谢。我仍然掌握着ddply的窍门,这真的把事情弄清楚了。
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")
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)