Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用“…”拆分函数的数组参数&引用;R_R_Function_Arguments - Fatal编程技术网

使用“…”拆分函数的数组参数&引用;R

使用“…”拆分函数的数组参数&引用;R,r,function,arguments,R,Function,Arguments,以下函数创建一个data.frame,其中n列作为参数数 functionWithDots <- function(...) { f1 <- function(x) c(x,x+4) list <- list(...) list <- lapply(list, f1) expand.grid(list) } 结果是 id Var1 一, 二, 五, 六, 既然传递时它似乎返回不同的结果,比如说,“1,2,3”而不是“c(1,2,3)”,那么我如

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

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

  • id Var1
  • 一,
  • 二,
  • 五,
  • 六,

既然传递时它似乎返回不同的结果,比如说,“1,2,3”而不是“c(1,2,3)”,那么我如何将正确的无关联参数传递给该函数呢?

假设我正确理解了这个问题,也就是说,OP希望通过使用DOTS在
函数中传递
1,2
1:2
来获得相同的结果,这里有一种解决方法。对于这两种情况,我们将
..
中的元素转换为
列表
,它应该为这两种情况提供相同的结果

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

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

在第二种情况下,它返回一个
列表
,其长度等于输入中的元素数

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

函数带点如果您的参数在“列表”/“向量”中,您也可以使用
do.call
args=1:2;do.call(functionWithDots,as.list(args))
functionWithDots <- function(...) {
  f1 <- function(x) c(x,x+4)
  list <- list(...)
  print(list)
}
functionWithDots(1:2)
#[[1]]
#[1] 1 2
functionWithDots(1,2)
#[[1]]
#[1] 1

#[[2]]
#[1] 2
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