在reshape2中使用min或max时,没有非缺失参数警告

时间:2014-06-18 09:57:14

标签: r aggregate-functions reshape2

当我在reshape2包中的dcast函数中使用min或max时,我收到以下警告。它告诉我什么?我找不到任何可以解释警告信息的内容,而且当我使用max而不是当我使用mean或其他聚合函数时,我对它的原因感到有点困惑。

  

警告信息:
在.fun(.value [0],...)中:min没有非缺失参数;返回Inf

这是一个可重复的例子:

data(iris)

library(reshape2)

molten.iris <- melt(iris,id.var="Species")
summary(molten.iris)
str(molten.iris)
#------------------------------------------------------------
# Both return warning:
dcast(data=molten.iris,Species~variable,value.var="value",fun.aggregate=min)
dcast(data=molten.iris,Species~variable,value.var="value",fun.aggregate=max)

# Length looks fine though
dcast(data=molten.iris,Species~variable,value.var="value",fun.aggregate=length)

#------------------------------------------------------------
# No warning messages here:
aggregate(value ~ Species + variable, FUN=min, data=molten.iris)
aggregate(value ~ Species + variable, FUN=max, data=molten.iris)
#------------------------------------------------------------
# Or here:
library(plyr)

ddply(molten.iris,c("Species","variable"),function(df){
  data.frame(
    "min"=min(df$value),
    "max"=max(df$value)
    )
})
#------------------------------------------------------------

1 个答案:

答案 0 :(得分:38)

您收到此警告,因为min / max应用于长度为0的参数的数字。

这会再现警告。

min(numeric(0))
[1] Inf
Warning message:
In min(numeric(0)) : no non-missing arguments to min; returning Inf

请注意,对于mean,您不会收到警告:

mean(numeric(0))
[1] NaN

这只是一个警告,对计算没有任何影响。您可以使用suppressWarnings

来禁止它
 suppressWarnings(dcast(data=molten.iris,
                  Species~variable,value.var="value",
                  fun.aggregate=min))

修改

上面我只是回答这个问题:警告的含义是什么?为什么我们有这个最小/最大而不是平均功能。问题为dcast将聚合函数应用于长度为0的向量的问题,它只是一个BUG,您应该联系包维护者。我认为错误来自plyr::vaggregate内部使用的dcast函数,

plyr::vaggregate(1:3,1:3,min)
Error in .fun(.value[0], ...) : 
  (converted from warning) no non-missing arguments to min; returning Inf

特别是这行代码:

plyr::vaggregate
function (.value, .group, .fun, ..., .default = NULL, .n = nlevels(.group)) 
{
    ### some lines       
    ....
    ### Here I don't understand the meaning of .value[0]
    ### since vector in R starts from 1 not zeros!!!
    if (is.null(.default)) {
        .default <- .fun(.value[0], ...)
    }
    ## the rest of the function 
    .....
}