r - 使用 "..."R 拆分函数的数组参数

标签 r function arguments

以下函数创建一个 data.frame,其中 n 列作为参数的数量

functionWithDots <- function(...) {
  f1 <- function(x) c(x,x+4)
  list <- list(...)
  list <- lapply(list, f1)
  expand.grid(list)
  }

当运行它时
functionWithDots(1,2)
预期的结果是:
  • id 变量 1 变量 2
  • 1 2
  • 5 2
  • 1 6
  • 5 6

  • 而如果我通过将“(1,2)”替换为“1:2”来做同样的事情
    functionWithDots(1,2)
    

    结果是
  • id 变量 1
  • 1
  • 2
  • 5
  • 6

  • 如何将正确的未连接参数传递给该函数,因为它在传递时似乎返回不同的结果,比如说“1,2,3”而不是“c(1,2,3)”?

    最佳答案

    假设我正确理解了问题,即。 OP 希望通过传递 1,2 来获得相同的结果和 1:2functionWithDots ,这是修复它的一种方法。我们转换 ... 中的元素至 list对于这两种情况,它应该为两种情况提供相同的结果。

    functionWithDots <- function(...) {
       f1 <- function(x) c(x,x+4)
       dots <- c(...)
       list <- as.list(dots)
       list <- lapply(list, f1)
       expand.grid(list)
     }
    
    
    functionWithDots(1,2)
    #  Var1 Var2
    #1    1    2
    #2    5    2
    #3    1    6
    #4    5    6
     functionWithDots(1:2)
    #  Var1 Var2
    #1    1    2
    #2    5    2
    #3    1    6
    #4    5    6
    

    1:3 核对对比 1,2,3
    functionWithDots(1,2,3)
    #  Var1 Var2 Var3
    #1    1    2    3
    #2    5    2    3
    #3    1    6    3
    #4    5    6    3
    #5    1    2    7
    #6    5    2    7
    #7    1    6    7
    #8    5    6    7
    
    functionWithDots(1:3)
    #  Var1 Var2 Var3
    #1    1    2    3
    #2    5    2    3
    #3    1    6    3
    #4    5    6    3
    #5    1    2    7
    #6    5    2    7
    #7    1    6    7
    #8    5    6    7
    

    现在,让我们看看 OP 函数中的问题(删除了 lapplyexpand.grid )
    functionWithDots <- function(...) {
      f1 <- function(x) c(x,x+4)
      list <- list(...)
      print(list)
    }
    

    第一种情况 1:2 ,该函数返回 listlength 1
    functionWithDots(1:2)
    #[[1]]
    #[1] 1 2
    

    而在第二个中,它返回一个 list长度等于输入中的元素数
    functionWithDots(1,2)
    #[[1]]
    #[1] 1
    
    #[[2]]
    #[1] 2
    

    在修改后的函数中,两者都返回 list长度等于输入参数中的元素数。
    functionWithDots <- function(...) {
      f1 <- function(x) c(x,x+4)
      dots <- c(...)
      list <- as.list(dots)
      print(list) 
     }
    
    functionWithDots(1:2)
    #[[1]]
    #[1] 1
    
    #[[2]]
    #[1] 2
    
    functionWithDots(1,2)
    #[[1]]
    #[1] 1
    
    #[[2]]
    #[1] 2
    

    关于r - 使用 "..."R 拆分函数的数组参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32007458/

    相关文章:

    r - 如何将数字数据转换为 R 中的货币?

    使用 dplyr 管道替换对角线元素

    R:用最后一个非空单元格的值填充空单元格

    r - 根据data.table中一列的值改变多列的值

    javascript - 将 PHP var 传递给 js 函数

    c++ - 如何创建不同原型(prototype)的函数指针数组?

    c - 如何检查给定参数是否是另一个给定参数的子字符串

    Android 内容解析器查询占位符整数

    javascript - (function() {})() 构造如何工作以及人们为什么使用它?

    java - 程序中未触发异常处理/意外行为