对所有参数组合应用一个函数

18

我希望能够对一组输入参数的所有组合应用一个函数。我有一个可行的解决方案(如下),但如果没有更好/更通用的方法来使用plyr等,则会感到惊讶,但到目前为止还没有找到任何东西。是否有更好的解决方案?

# Apply function FUN to all combinations of arguments and append results to
# data frame of arguments
cmapply <- function(FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE, 
    USE.NAMES = TRUE)
{
    l <- expand.grid(..., stringsAsFactors=FALSE)
    r <- do.call(mapply, c(
        list(FUN=FUN, MoreArgs = MoreArgs, SIMPLIFY = SIMPLIFY, USE.NAMES = USE.NAMES), 
        l
    ))
    if (is.matrix(r)) r <- t(r) 
    cbind(l, r)
}

示例:

# calculate sum of combinations of 1:3, 1:3 and 1:2
cmapply(arg1=1:3, arg2=1:3, 1:2, FUN=sum)

# paste input arguments
cmapply(arg1=1:3, arg2=c("a", "b"), c("x", "y", "z"), FUN=paste)

# function returns a vector
cmapply(a=1:3, b=2, FUN=function(a, b) c("x"=b-a, "y"=a+b))

5
“更好”的意思是什么?你已经有的东西似乎非常出色。 - Roland
@nicola 不确定你的意思:他只是在硬编码内部赋值。SIMPLIFY 的值是用户在调用 cmapply 时设置的。 - Carl Witthoft
@nicloa/@Carl - 在这些注释之间,我进行了一次编辑,可能可以解释混淆的原因。但是我不确定如何直接调用mapply。 - waferthin
你是对的,你需要使用 do.call - nicola
啊,明白了。又骗到我了。 - Carl Witthoft
显示剩余4条评论
2个回答

1
这个函数并不一定更好,只是略有不同:
rcapply <- function(FUN, ...) {

  ## Cross-join all vectors
  DT <- CJ(...)

  ## Get the original names
  nl <- names(list(...))

  ## Make names, if all are missing
  if(length(nl)==0L) nl <- make.names(1:length(list(...)))

  ## Fill in any missing names
  nl[!nzchar(nl)] <- paste0("arg", 1:length(nl))[!nzchar(nl)]
  setnames(DT, nl)

  ## Call the function using all columns of every row
  DT2 <- DT[,
            as.data.table(as.list(do.call(FUN, .SD))), ## Use all columns...
            by=.(rn=1:nrow(DT))][ ## ...by every row
              , rn:=NULL] ## Remove the temp row number

  ## Add res to names of unnamed result columns
  setnames(DT2, gsub("(V)([0-9]+)", "res\\2", names(DT2)))

  return(data.table(DT, DT2))
}

head(rcapply(arg1=1:3, arg2=1:3, 1:2, FUN=sum))
##    arg1 arg2 arg3 res1
## 1:    1    1    1    3
## 2:    1    1    2    4
## 3:    1    2    1    4
## 4:    1    2    2    5
## 5:    1    3    1    5
## 6:    1    3    2    6

head(rcapply(arg1=1:3, arg2=c("a", "b"), c("x", "y", "z"), FUN=paste))
##    arg1 arg2 arg3  res1
## 1:    1    a    x 1 a x
## 2:    1    a    y 1 a y
## 3:    1    a    z 1 a z
## 4:    1    b    x 1 b x
## 5:    1    b    y 1 b y
## 6:    1    b    z 1 b z

head(rcapply(a=1:3, b=2, FUN=function(a, b) c("x"=b-a, "y"=a+b)))
##    a b  x y
## 1: 1 2  1 3
## 2: 2 2  0 4
## 3: 3 2 -1 5

0

您原始代码的稍微简化版本:

cmapply <- function(FUN, ..., MoreArgs = NULL)
{
    l <- expand.grid(..., stringsAsFactors=FALSE)
    r <- .mapply(FUN=FUN, dots=l, MoreArgs = MoreArgs)
    r <- simplify2array(r, higher = FALSE)
    
    if (is.matrix(r)) r <- t(r)
    return(cbind(l, r))
}

这不需要使用do.call

它确实缺少SIMPLIFYUSE.NAMES参数,但是您使用的方式似乎使参数无法使用:如果SIMPLIFY = FALSE,则rbind()将失败,并且USE.NAMES = TRUE不起作用,因为名称在rbind()之后会丢失。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接