r - 将函数应用于所有参数组合

标签 r mapply

我希望能够将函数应用于一组输入参数的所有组合。我有一个可行的解决方案(如下),但是如果没有更好的/更通用的方法来使用它,将会感到惊讶,例如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))

最佳答案

此功能不一定更好,只是稍有不同:

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

关于r - 将函数应用于所有参数组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25911463/

相关文章:

r - 提取 Changeabel 字符串的一部分

r - 将 Data.Tables (R) 与循环或 mapply 组合

r - mapply 有多个参数,其中一个参数是常量(数据)

在 R 中使用 lapply 进行 t 检验时删除 NA

r - R中循环变量与数据表的乘积组合

r - 无法在函数中将字符串传递给 require()?

r - NavbarMenu 中的 NavbarMenu in Shiny

python - 遍历多个列表的相应元素

r - Map() 和 dplyr 连接

r - 检测 R 中的可用和空闲内核