R reshape2中的cast()调用的自定义聚合函数出错

use*_*694 8 casting aggregate r reshape reshape2

我想使用R将具有非唯一rownames的表中的数值数据汇总到具有唯一行名的结果表,其中值使用自定义函数进行汇总.摘要逻辑是:如果最大值与最小值的比率<1.5,则使用值的均值,否则使用中值.因为表非常大,我试图在reshape2包中使用melt()和cast()函数.

# example table with non-unique row-names
tab <- data.frame(gene=rep(letters[1:3], each=3), s1=runif(9), s2=runif(9))
# melt
tab.melt <- melt(tab, id=1)
# function to summarize with logic: mean if max/min < 1.5, else median
summarize <- function(x){ifelse(max(x)/min(x)<1.5, mean(x), median(x))}
# cast with summarized values
dcast(tab.melt, gene~variable, summarize)

上面的最后一行代码会导致错误通知.

Error in vapply(indices, fun, .default) : 
  values must be type 'logical',
 but FUN(X[[1]]) result is type 'double'
In addition: Warning messages:
1: In max(x) : no non-missing arguments to max; returning -Inf
2: In min(x) : no non-missing arguments to min; returning Inf

我究竟做错了什么?请注意,如果汇总函数只返回min()或max(),则没有错误,尽管有关于"没有非缺失参数"的警告消息.谢谢你的任何建议.

(我想要使用的实际表格是200x10000.)

小智 9

简答:提供填充值如下acast(tab.melt,gene~variable,summarize,fill = 0)

答案很长:看来你的函数在被传递到vaggregate函数中的vapply之前被包装如下(dcast调用cast调用vaggregate调用vapply):

fun <- function(i) {
    if (length(i) == 0) 
        return(.default)
    .fun(.value[i], ...)
}
Run Code Online (Sandbox Code Playgroud)

要找出.default应该是什么,执行此代码

if (is.null(.default)) {
    .default <- .fun(.value[0])
}
Run Code Online (Sandbox Code Playgroud)

即.value [0]传递给函数.当x为数字(0)时,min(x)或max(x)返回Inf或-Inf.但是,max(x)/ min(x)返回具有类逻辑的NaN.所以当vapply执行时

vapply(indices, fun, .default)
Run Code Online (Sandbox Code Playgroud)

如果默认值为class logical(由vapply用作模板),则该函数在开始返回双精度时失败.


koh*_*ske 2

dcast() 尝试将缺少的组合的值设置为默认值。

您可以通过 fill 参数指定它,但如果 fill=NULL,则使用 fun(0-lenght vector) 返回的值(即此处的 summarise(numeric(0)) )作为默认值。

请参阅?dcast

那么,这是一个解决方法:

 dcast(tab.melt, gene~variable, summarize, fill=NaN)
Run Code Online (Sandbox Code Playgroud)