Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 按因子值将数据帧分成子集,发送到返回glm类的函数,如何重新组合?_R_Plyr - Fatal编程技术网

R 按因子值将数据帧分成子集,发送到返回glm类的函数,如何重新组合?

R 按因子值将数据帧分成子集,发送到返回glm类的函数,如何重新组合?,r,plyr,R,Plyr,由于Hadley的plyr包ddply函数,我们可以获取一个数据帧,按因子将其分解为子数据帧,将每个子数据帧发送给一个函数,然后将每个子数据帧的函数结果合并成一个新的数据帧 但是,如果函数返回一个类的对象,比如glm,或者在我的例子中,返回一个c(“glm”,“lm”),该怎么办。那么,这些不能组合成一个数据帧,是吗?我得到了这个错误 Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = string

由于Hadley的plyr包ddply函数,我们可以获取一个数据帧,按因子将其分解为子数据帧,将每个子数据帧发送给一个函数,然后将每个子数据帧的函数结果合并成一个新的数据帧

但是,如果函数返回一个类的对象,比如glm,或者在我的例子中,返回一个c(“glm”,“lm”),该怎么办。那么,这些不能组合成一个数据帧,是吗?我得到了这个错误

Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) : cannot coerce class 'c("glm", "lm")' into a data.frame
是否有更灵活的数据结构来容纳函数调用的所有复杂glm类结果,从而保留有关dataframe子集的信息


还是应该以完全不同的方式来实现这一点?

仅扩展我的评论:
plyr
具有一组组合输入和输出类型的函数。因此,当您的函数返回一些不可转换到
data.frame
的内容时,您应该使用
list
作为输出。因此,不要使用
ddply
而是使用
dlply

当你想在每个模型上做些什么,并将结果转换成
数据时,frame
ldply
是关键

让我们使用
dlply

list_of_models <- dlply(warpbreaks, .(tension), function(X) lm(breaks~wool, data=X))
str(list_of_models, 1)
# List of 3
#  $ L:List of 13
#   ..- attr(*, "class")= chr "lm"
#  $ M:List of 13
#   ..- attr(*, "class")= chr "lm"
#  $ H:List of 13
#   ..- attr(*, "class")= chr "lm"
#  - attr(*, "split_type")= chr "data.frame"
#  - attr(*, "split_labels")='data.frame':        3 obs. of  1 variable:
  • 每个模型的统计信息如下:

    ldply(list_of_models, function(model) {
        data.frame(fit=predict(model, warpbreaks))
    })
    #     tension     fit
    # 1         L 44.5556
    # 2         L 44.5556
    # 3         L 44.5556
    
    ldply(list_of_models, function(model) {
      c(
        aic = extractAIC(model),
        deviance = deviance(model),
        logLik = logLik(model),
        confint = confint(model),
        coef = coef(model)
      )
    })
    # tension aic1    aic2 deviance   logLik confint1  confint2 confint3 confint4 coef.(Intercept) coef.woolB
    # 1       L    2 98.3291  3397.78 -72.7054  34.2580 -30.89623  54.8531 -1.77044          44.5556  -16.33333
    # 2       M    2 81.1948  1311.56 -64.1383  17.6022  -4.27003  30.3978 13.82559          24.0000    4.77778
    # 3       H    2 76.9457  1035.78 -62.0137  18.8701 -13.81829  30.2411  2.26273          24.5556   -5.77778
    

  • 您是否尝试了
    dlply
    ?输出是一个列表。你说得对,谢谢,dlply有效。返回的分层列表是我不熟悉的,我不知道是否可以以某种可伸缩的方式重新分配回dataframe结构,但这可能只是我理解列表切片等更好的方法的问题。