【发布时间】:2014-08-08 13:43:33
【问题描述】:
当我在 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)
)
})
#------------------------------------------------------------
【问题讨论】:
-
使用
min或max而不是mean时出现这种情况的原因是mean在应用于长度为0 的向量时不会引发警告。如果您执行dcast(data=molten.iris,Species~variable,value.var="value", function(x) {print(x); min(x)}),您会看到第一个x是长度为0 的数字向量。由于默认情况下dcast中的fill=NULL,然后min被应用于长度为0 的向量并产生警告。问题是为什么存在这种结构模式,即返回的第一个元素的长度为 0 向量......不知道为什么会发生这种情况,因为所有因素组合似乎都存在
标签: r aggregate-functions reshape2