首页 文章

用于R中的回归的ddply

提问于
浏览
3

I 'm I have a data frame that contains an '输出',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

因此,基于温度,湿度和时间因素,我希望这里有三个城市的三个模型 .

1 回答

  • 5

    通过使用 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)
    

    这段代码更加冗长,但在出现问题时更容易检查和分析 .

相关问题