使用“ ...” R分割函数的数组参数

Fed*_*ico 5 arguments r function

以下函数创建一个具有n列作为参数数量的data.frame

functionWithDots <- function(...) {
  f1 <- function(x) c(x,x+4)
  list <- list(...)
  list <- lapply(list, f1)
  expand.grid(list)
  }
Run Code Online (Sandbox Code Playgroud)

作为functionWithDots(1,2)运行时,预期结果是:

  • id Var1 Var2
    1. 1 2
    2. 5 2
    3. 1 6
    4. 5 6

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

functionWithDots(1,2)
Run Code Online (Sandbox Code Playgroud)

结果是

  • id Var1
    1. 1个
    2. 2
    3. 5
    4. 6

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

akr*_*run 3

假设我正确理解了这个问题,即。OP 希望通过传递1,21:2来获得相同的结果functionWithDots,这是修复它的一种方法。我们将这两种情况的元素转换...为,并且这两种情况应该给出相同的结果。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
Run Code Online (Sandbox Code Playgroud)

1:3用vs检查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
Run Code Online (Sandbox Code Playgroud)

现在,让我们看看OP函数中的问题(删除了lapplyand expand.grid

functionWithDots <- function(...) {
  f1 <- function(x) c(x,x+4)
  list <- list(...)
  print(list)
}
Run Code Online (Sandbox Code Playgroud)

在第一种情况下1:2,该函数返回a listof length1

functionWithDots(1:2)
#[[1]]
#[1] 1 2
Run Code Online (Sandbox Code Playgroud)

而在第二个中,它返回一个list长度等于输入中元素数量的

functionWithDots(1,2)
#[[1]]
#[1] 1

#[[2]]
#[1] 2
Run Code Online (Sandbox Code Playgroud)

在修改后的函数中,两者返回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
Run Code Online (Sandbox Code Playgroud)